Reputation: 3779
I have a model that is many-to-one with users. But when I submit a form based on that model, I am not correctly providing the user.
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
The view says this:
@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!
Thanks for any tips.
Upvotes: 0
Views: 66
Reputation: 599600
Don't set the user or salt on the form instance, it has no idea what to do with it. Set it on the Thing that is generated from form.save
.
thing = form.save(commit=False)
thing.salt = whatever
thing.user = myuser
thing.save()
Upvotes: 1