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.
class MyForm(forms.ModelForm):
class Meta:
fields = ('field1', 'field2')
model = MyModel
def create_or_update(request):
if request.method == 'POST':
form = MyForm(request.POST)
if form.is_valid():
m = form.save(commit=False)
m.field3 = 'blah'
m.field4 = 'blah'
m.save()
request.session['m'] = m
return HttpResponseRedirect(reverse('enter_cc_info'))
...
else:
m = request.session.get('m', None)
if m:
instance = get_object_or_None(MyModel, id=m.id)
if instance:
form = MyForm(instance=instance)
else:
form = MyForm({'field1': m.field1, 'field2': m.field2})
else:
form = MyForm()
...
, , , , . , POST, , form.save().
, , , HTML ( ) . , "pk" "id" ( ), .
, , , . .