0
我有一個與用戶多對一的模型。但是,當我根據該模型提交表單時,我沒有正確地提供用戶。ForeignKey和表單提交
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!
感謝您的任何提示。
啊,完美!謝謝。 – jma