Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update an object from edit form in Django?

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?

like image 932
Herman Schaaf Avatar asked Jan 12 '11 20:01

Herman Schaaf


People also ask

What is form Is_valid () in django?

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.

How do I override a django form?

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.


2 Answers

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.

like image 184
Mikhail Korobov Avatar answered Oct 23 '22 05:10

Mikhail Korobov


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})  
like image 30
user3817584 Avatar answered Oct 23 '22 07:10

user3817584