我有一个模型,用户有ManyToManyField
,我希望在他/她在Choice
模型中提交表单时记录登录用户,但此代码阻止我这样做。我使用login_required
装饰器强制用户先登录(这就是我想要的)。
models.py:
from django.db import models
from django.contrib.auth.models import User
QUESTION_CHOICES = (
("choice_1", "Choice 1"),
("choice_2", "Choice 2"),
("choice_3", "Choice 3"),
)
class Choice(models.Model):
users = models.ManyToManyField(User)
choices = models.CharField(max_length=256, choices=QUESTION_CHOICES, unique=True)
vote = models.IntegerField(default=0)
def __str__(self):
return self.choices + " " + "-" + " " + str(self.vote)
views.py:
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from .models import Choice
@login_required
def index(request):
food = request.POST.get('sunday')
user_v = None
get_choices = Choice.objects.values('choices', 'vote')
new_choices = list(get_choices)
for q in new_choices:
choice = q['choices']
vote_v = q['vote']
if food:
if food == choice:
if request.user.is_authenticated():
user_v = request.user
print(user_v) # it prints out correctly after sucessful form submit
vote_v += 1
model_conn = Choice.objects.get(choices=choice)
model_conn.vote = vote_v
model_conn.users = user_v # this is where I get an error
model_conn.save()
return render(request, 'index.html', {})
答案 0 :(得分:1)
您正在为用户使用ManyToMany字段,因此需要使用add
方法将当前用户添加到用户列表中:
model_conn.users.add(user_v)
如果您需要先清除相关用户列表,可以使用clear
:
model_conn.users.clear()
model_conn.users.add(user_v)