from .models import Sensor
from .models import Sensor, Measurment
class SenorsListView(generic.ListView):
model = Sensor
context_object_name = 'sensors_list'
template_name = 'sensors_list.html'
queryset = Sensor.objects.all().order_by('-date_start')
{% extends "base_generic.html" %}
{% block content %}
<h1>Sensors List</h1>
{% if sensors_list %}
<table class="table">
<tr>
<td><h4>ID датчика<h4></td>
<td><h4>Дата установки<h4></td>
<td><h4>Долгота<h4></td>
<td><h4>Широта<h4></td>
<td><h4>Данные последнего измерения<h4></td>
</tr>
{% for sensor in sensors_list %}
<tr>
<td>{{sensor.id}}</td>
<td>{{sensor.date_start}}</td>
<td>{{sensor.Latitude}}</td>
<td>{{sensor.Longitude}}</td>
# Данные последнего датчика
<td>{{sensor.measurment_set.last.temperature1}}</td>
</tr>
{% endfor %}
</table>
{% else %}
<p>There are no sensors in the DB.</p>
{% endif %}
{% endblock %}
dataAddPatient = formAddPatient.save()
surName = formAddInsurancePolicy.cleaned_data['surName']
...
newPolicy = InsurancePolicy(surName=surName, ... , id_patient=dataAddPatient)
newPolicy.save()
from django.db.models.signals import post_save
from django.dispatch import receiver
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
...
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.profile.save()
def __str__(self):
return self.user
from pytils import translit
class Book(models.Model):
def get_image_path(self, filename):
path = ''.join(["pictures/",translit.slugify(filename)])
return path
...
image = models.ImageField(verbose_name='Изображение', upload_to=get_image_path)
from django.forms import inlineformset_factory
class QCWorkConstructionCreateView(TemplateView):
template_name = 'executive/qc/qc-work-construction-create.html'
def get_context_data(self, **kwargs):
context = super(QCWorkConstructionCreateView, self).get_context_data(**kwargs)
works = Work.objects.filter(id__in=self.request.GET.getlist('works'))
# задаем начальные значения
initial = []
for work in works:
for con in work.constructions.all():
qc_con = dict()
qc_con['construction'] = con.id
qc_con['work'] = work.id
qc_con['value'] = ''
initial.append(qc_con)
# количество отображаемых строк formset
extra = len(initial)
# форма для документа QC
form = QCForm(self.request.user, {'object': self.request.user.profile.current_object_id})
# Formset для QCConstruction
QCformset = inlineformset_factory(QualityControl, QCConstruction, fields=('construction', 'work', 'value',), extra=extra)
context['form'] = form
context['formset'] = QCformset(initial=initial)
return context
def post(self, *args, **kwargs):
form = QCForm(self.request.user, self.request.POST)
if form.is_valid():
qc = form.save()
QCformset = inlineformset_factory(QualityControl, QCConstruction, fields=('construction', 'work', 'value',))
formset = QCformset(self.request.POST, instance=qc)
if formset.is_valid():
formset.save()
return redirect('qc_list')
...
next_number = Order.objects.count() + 1
form = OrderForm({'оrder_number': next_number})
...
function ajax_post(url, form_id, block_id) {
var form = $(form_id).serialize();
$.ajax({
url: url,
type: 'POST',
data: form,
dataType: 'html',
success: function (data) {
$(block_id).html(data);
}
});
return false;
}
<form action="javascript:void(null);" onsubmit="ajax_post('{% url 'companies' project %}', '#project_company_form',
'#content')" id="project_company_form">
{% csrf_token %}
{{ form.company }}
....
<button type="submit"> Add </button>
</form>
class RegistrationForm(UserCreationForm):
email = forms.EmailField(required=True, widget=forms.TextInput(attrs={'placeholder': 'Электронный адрес'}))
class Meta:
model = User
fields = ('first_name', 'last_name', 'email', 'password1', 'password2')
# clean email field
def clean_email(self):
email = self.cleaned_data["email"]
try:
User.objects.get(email=email)
except User.DoesNotExist:
return email
raise forms.ValidationError('Такой адрес электронной почты уже зарегестрирован.')
# modify save() method so that we can set user.is_active to False when we first create our user
def save(self, commit=True):
user = super(RegistrationForm, self).save(commit=False)
user.username = self.cleaned_data['email']
user.email = self.cleaned_data['email']
if commit:
user.is_active = False # not active until he opens activation link
user.save()
return user
class DocumentForm(forms.ModelForm):
def __init__(self, project, *args, **kwargs):
super(DocumentForm, self).__init__(*args, **kwargs)
self.fields['organization'].queryset = Company.objects.filter(projectcompany__project=project)
class Meta:
model = Documents
fields = ('__all__')