2011-09-30 72 views
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! 

感謝您的任何提示。

回答

1

不要在表單實例上設置用戶或鹽,它不知道如何處理它。將它設置在從form.save生成的物品上。

thing = form.save(commit=False) 
thing.salt = whatever 
thing.user = myuser 
thing.save() 
+0

啊,完美!謝謝。 – jma