P
P
Pavel2017-04-06 03:55:17
Django
Pavel, 2017-04-06 03:55:17

What is the correct way to write a view to process the form and create a model object?

Help with closure please.
There are models:

class Contract(models.Model):
  ...
    responsible = models.ManyToManyField(Responsible, blank=True)
  ...

class Responsible(models.Model):
    Responsible_name = models.CharField(max_length = 50)

class Resp_status(models.Model):
    responsible = models.ForeignKey(Responsible)
    approval = models.BooleanField(default = False)
    contract = models.ForeignKey(Contract, null = True)

There is a form for the Contract model to create a contract. How can I make sure that when creating a contract, a Resp_status is created for each of the selected Responsibles?
I'm trying to do this:
def new_contract(request, pk):
    partner = Partner.objects.get(id=pk)
    if request.method == 'POST':
        form = NewContractForm(request.POST)
        if form.is_valid():
            contract = form.save(commit=False)
            contract.partner = partner
            contract.save()
            for resp in contract.responsible.all():
                status.responsible = resp
                status.contract = contract.id 
                status.save()

It turns out that we fill out the form, a Contract is created, and after its creation, we need to create statuses for all selected responsible.
And it’s completely impossible to formulate a query for Google to find a solution. Perhaps I am initially somehow incorrectly approaching the solution of the problem?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
StasShk, 2017-04-06
@StasShk

Maybe just like this?

...
    for resp in contract.responsible.all():
            s = Resp_status.objects.create(responsible=resp,  contrac =contract.id)
            s.save()

F
FeNUMe, 2017-04-06
@FeNUMe

You already have a list of all responsible in contract.responsible in the function, why are you doing the extra. request to the database to receive it?

resp_status_all=[]
for r in contract.responsible:
    resp_status_all.append(Resp_status(responsible=r,  contract = contract.id))
Resp_status.objects.bulk_create(resp_status_all)

But as sim3x rightly noted, your code leaves much to be desired: at least read the dzhang code guide to correctly name entities; also carefully review the logic of your application for the presence of looped requests to the database and replace them with either bulk_create or manually collected requests from Q () so as not to load the database.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question