我有一个与用户多对一的模型。但是当我根据该模型提交表单时,我没有正确地提供用户。
class Thing(models.Model):
"""Things."""
user = models.ForeignKey(User)
salt = models.IntegerField()
# [...]
class GenerateThingForm(ModelForm):
"""A form for registering a new Thing."""
class Meta:
model = Thing
fields = (...) # There are some, but it would distract here
该观点说明了这一点:
@login_required()
def register_thing(request):
"""Register Thing."""
if request.method == 'POST': # If the form has been submitted...
form = GenerateThingForm(request.POST)
if form.is_valid():
form.salt = random.getrandbits(32)
# Apparently I need to specify form.user.
# Same result if just request.user
form.user = User.objects.get(request.user)
form.save() # Oh, no! 'user_id' is null!
感谢您的任何提示。
答案 0 :(得分:1)
不要在表单实例上设置用户或salt,它不知道如何处理它。将其设置在从form.save
。
thing = form.save(commit=False)
thing.salt = whatever
thing.user = myuser
thing.save()