Django Database Form and Form

I have a complex django object that has properties of other class types. This happens as follows:

class Order:
   contractor - type Person
   some other fields....

In my form, I would like to be able to either select an existing Person object from the drop-down list, or add a new one with the form. I managed to create the forms and the corresponding workflow, but the problem is saving the order itself, I just can’t get the identifier of the saved instance of Person. I do like this:

def make_order(request):
  if request.method == 'POST':
    parameters = copy.copy(request.POST)
    contractor_form = ContractorForm(parameters)
    if contractor_form.is_valid():
      contractor_form.save()
      parameters['contractor'] = ???
    form = OrderForm(parameters)
    if form.is_valid():
      form.save() 
      return HttpResponseRedirect('/orders/')
  else:
    form = OrderForm()
    contractor_form = ContractorForm()

  return render_to_response('orders/make_order.html', {'order_form' : form, 'contractor_form' : contractor_form})

So, if the POST request reaches this method, I first check if the ContractorForm is filled out - I assume that if the form is valid, it is intended to be used. If so, then I will save it and would like to assign the database identifier of the saved object to the corresponding field for OrderForm in order to find it.

- ModelForms.

:

  • ? ( ) - pythonic; -)
  • ModelForms?

Edited

My ContractorForm:

class ContractorForm(ModelForm):
  class Meta:
    model = Contractor

.

+3
1

save() .

if contractor_form.is_valid():
  instance = contractor_form.save()
  parameters['contractor'] = instance

id instance.id instance.pk.

pk vs. id:

, , Django , pk. , . , , .

:

, , - .

models.py

class Category(models.Model):
    name = models.CharField(max_length=70)
    slug = models.SlugField()

forms.py

from django import forms
from models import Category

class MyModelForm(forms.ModelForm):
    class Meta:
        model = Category

:

In [3]: from katalog.forms import MyModelForm
In [4]: data = {'name':'Test', 'slug':'test'}
In [5]: form = MyModelForm(data)
In [6]: instance = form.save()
In [7]: instance
Out[7]: <Category: Test>
In [8]: instance.id
Out[8]: 5L
+7

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


All Articles