Django ModelForms - "instance" does not work as expected

I have a model that will either create a new model or edit an existing one - it should just work, but for some reason I get a new instance every time.

The script is the first step in an e-commerce order. The user must fill in some information describing the order (which is stored in the model). I create a model, save it, and then redirect it to the next view so that the user can enter their cc information. I stick to the model in the session, so I don’t need to search the database in the next view. The template has a link for the second view (cc info), which allows the user to return to the first view to edit their order.

# forms.py

class MyForm(forms.ModelForm):
    class Meta:
        fields = ('field1', 'field2')
        model = MyModel

# views.py

def create_or_update(request):
    if request.method == 'POST':
        form = MyForm(request.POST)
        if form.is_valid():
            m = form.save(commit=False)
            # update some other fields that aren't in the form
            m.field3 = 'blah'
            m.field4 = 'blah'
            m.save()
            request.session['m'] = m
            return HttpResponseRedirect(reverse('enter_cc_info'))
        # invalid form, render template
        ...
    else:
        # check to see if we're coming back to edit an existing model
        # this part works, I get an instance as expected
        m = request.session.get('m', None)
        if m:
            instance = get_object_or_None(MyModel, id=m.id)
            if instance:
                form = MyForm(instance=instance)
            else:
                # can't find it in the DB, but it in the session
                form = MyForm({'field1': m.field1, 'field2': m.field2})
        else:
            form = MyForm()

    # render the form
    ...

, , , , . , POST, , form.save().

, , , HTML ( ) . , "pk" "id" ( ), .

, , , . .

+3
1

. . :

form = MyForm(request.POST)

request.POST? , , - , . , . , , POST, .

? , instance=instance, Form, . . . , , .

? URL- POST. . :

def create_or_update(request, instance_id):
#                             ^^^^^ 
#                             URL param
    if request.method == 'POST':
        instance = get_object_or_None(Model, pk = instance_id)
        # ^^^^^
        # Look up the instance

        form = MyForm(request.POST, instance = instance)
        #                           ^^^^^^^
        #                           pass the instance now.
        if form.is_valid():
              ....
+9

Source: https://habr.com/ru/post/1768275/


All Articles