Possibly a newbie question, so please bear with me.
I have a Django form that edits a certain instance of a Model. In order to know which object is being edited, I have a hidden field containing the id of the object, along with the URL containing the id.
First question: Is having the id of the object in a hidden field the right way of doing it?
My (possibly unfounded) concern with having it only as part of the url is that someone could then open the page of one object id, submit the form to another, and that object will then be overwritten. That's why I'm trying to use a hidden field.
The problem with storing the id in a hidden field is that, on validation of the form, Django complains that the object does not have an unique id (obviously).
Second question: If a unique field is part of a form, how does one tell Django to ignore the fact that that key already exists, in order to update the object?
The is_valid() method is used to perform validation for each field of the form, it is defined in Django Form class. It returns True if data is valid and place all data into a cleaned_data attribute.
You can override forms for django's built-in admin by setting form attribute of ModelAdmin to your own form class. See: https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.form.
Why don't you just use ModelForm?
# forms.py
# ...
class MyForm(forms.ModelForm):
class Meta:
model = MyModel
# views.py
# ...
def my_view(request, id):
instance = get_object_or_404(MyModel, id=id)
form = MyForm(request.POST or None, instance=instance)
if form.is_valid():
form.save()
return redirect('next_view')
return render(request, 'my_template.html', {'form': form})
See https://docs.djangoproject.com/en/3.0/topics/forms/modelforms/#the-save-method for more details.
Update for Django 1.6 and further version
# forms.py
# ...
class MyForm(forms.ModelForm):
class Meta:
model = MyModel
# views.py
def my_view(request, id):
instance = MyModel.objects.get(id=id)
form = MyForm(request.POST or None, instance=instance)
if form.is_valid():
form.save()
return redirect('next_view')
return direct_to_template(request, 'my_template.html', {'form': form})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With