Answer the question
In order to leave comments, you need to log in
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)
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()
Answer the question
In order to leave comments, you need to log in
Maybe just like this?
...
for resp in contract.responsible.all():
s = Resp_status.objects.create(responsible=resp, contrac =contract.id)
s.save()
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)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question