简体   繁体   中英

Editing columns and sending data to database from views.py Django

my problem is that I can't make query directly in my views.py. I am writing app that allows user to take the test. But problem is that when I send filled form from the test page to my views.py and call form.save() , the query is not made in the exact moment, so I can't edit this query in the next lines of code. Is there any way that I could get around this? Some kind of form.send? Below is my code views.py:

if form is valid:
    form.save()     #i send data to DB
    choiceIndex = Choice.objects.latest('id').id
    choice = Choice.objects.get(pk=choiceIndex)
    choice.user = Users.objects.get(name=username)
    choice.save()   #i want to edit column made earlier
    return redirect("detail", question_id)         

models.py:

class Choice(models.Model):
    user = models.ForeignKey(Users, null=True, on_delete=models.CASCADE)
    question = models.ForeignKey(Questions, null=True,  on_delete=models.CASCADE)
    answer = models.CharField(null=True,max_length=50)

I'm guessing you want to add user to your newly created object? You'd do this like this:

if form.is_valid():
    obj = form.save(commit=False)
    obj.user = Users.objects.get(name=username)
    # or maybe you mean obj.user = request.user here?
    obj.save()
    return redirect("detail", question_id)

There is some information regarding this here in the Django docs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM