I have a Django model form which when I use the following, isn't saving
if request.method == 'POST':
form = AbsenceForm(request.POST, instance=request.user)
if form.is_valid():
form.save()
forms.py
class DateInput(forms.DateInput):
input_type = 'date'
class AbsenceForm(forms.ModelForm):
class Meta:
model = NotWorking
exclude = ['user']
widgets = {
'date': DateInput()
}
Can you help please.
You're using instance
wrong.
instance
on a model form is supposed to be of the same class as the model you're referring to. It is used in UpdateView
s to bind the form to an existing instance instead of creating a new instance up on save
.
Example from the documentation :
# Create a form to edit an existing Article, but use
# POST data to populate the form.
>>> a = Article.objects.get(pk=1)
>>> f = ArticleForm(request.POST, instance=a)
>>> f.save()
In order to attach the user instance to the form you should set it on the form instead of providing it as an instance
argument like detailed in this question .
if request.method == 'POST':
form = AbsenceForm(request.POST)
form
if form.is_valid():
instance = form.save(commit=False)
instance.user = request.user
instance.save()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.