class MyDateInput(forms.DateInput):
input_type = 'date'
format = '%d-%m-%Y'
class DocForm(forms.ModelForm):
class Meta:
model = Jurnal
fields = ['nomerdoc','datadoc',]
widgets = {
'nomerdoc': forms.TextInput(attrs={'class': 'form-control','id':'id_nomerdoc'}),
'datadoc': MyDateInput(attrs={'id':'id_datadoc'}),}
When I enter the data, everything works fine.But how do I insert a date into this field when editing a document?
Here is part of the code from my view:
if request.method=='POST':
form=OstDocForm(request.POST)
if form.is_valid():
form.save()
print('Saved')
last_id = Jurnal.objects.latest('id')
print(format(last_id.datadoc,'%d-%m-%Y'))
formHeader = OstDocForm(instance=last_id)
return render(request, 'store/Doc/UpdateNewOstDoc.html',
{'form': formHeader,'})
I fill out a document form and immediately want to open it on another page, with the possibility of editing. That’s what the data form is for…
That’s what it is now:
This isn’t supposed to appear in the “POST” part of your view, only in the “GET” part.
It may be helpful if you posted your entire view here.
Also, I suggest you review the Working with forms page, especially the section on the view to help your understanding of how things are supposed to work.
I need some fields to be filled in initially. And I enter the number and date manually. Then I open another page on which there will be a form with this data. At least that’s what I want to do.
In general, I want to do the following: there are two models
class Jurnal(models.Model):
oper=models.IntegerField(verbose_name="Код операции")
nomerdoc=models.CharField(max_length=50,verbose_name='Номер документа')
datadoc=models.DateTimeField(verbose_name='Дата документа')
class Meta:
verbose_name = 'Документ'
verbose_name_plural = 'Документы'
ordering = ['-datadoc', ]
class JurnalDoc(models.Model):
oper=models.IntegerField(max_length=1,verbose_name='Операция')
iddoc=models.ForeignKey(Jurnal,on_delete=models.PROTECT)
title = models.CharField(max_length=150, verbose_name='Наименование', )
price=models.FloatField(verbose_name='Цена',default=0.0)
In the first model, just the date and number of the document. The second one contains records related to the document. How do I fill this out? I think first write the data to the first table, get the last record to link to the second table. Then fill in the second table. How is it more correct to do this?
When you save a form, that function returns the object that was saved. You can then use the primary key of that object to set the foreign key field of the second object.
If you’re doing this in one page, you can do this directly. If you’re doing this on two pages, you’ll want to pass that primary key to the second page - generally as a url parameter.