0

我对如何在 Django 中为登录用户附加额外的表单有疑问。我希望附加表单属于登录用户,并且我在表单中输入的数据应该在登录用户表下。我是 Django 和 python 的新手,请耐心等待我希望我能正确解释我想用这个做什么

我将为此视图输入的数据应仅在登录用户下进行,基本上我只想将此视图附加到登录用户我得到的错误是异常值:

registration_todos.user_id 不能为 NULL

#models

class userProfile(models.Model):
    user = models.OneToOneField(User)
    birth =models.DateField()
    name = models.CharField(max_length=100)
    def __unicode__(self):
        return self.name



class todos(models.Model):
    user     = models.ForeignKey(User)
    title    = models.CharField(max_length=100)
    created  = models.DateField()
    time     = models.TimeField()
    def __unicode__(self):
            return unicode(self.user)

#forms   additional form for todos  
    class formtodos(ModelForm):
        title       = forms.CharField(label=(u'Todo'))
        created     = forms.DateField(label=(u'Date'))
        time        = forms.TimeField(label=(u'Time'))
        #user        = forms.CharField(label=(u'username'))
            class Meta:
               model = todos
               exclude=('user',) 
#view  
 def modeltodo(request):
if request.user.is_authenticated(): 
    todos.objects.filter(user=request.user)
if request.method == 'POST':
    form =formtodos(request.POST)
    if form.is_valid():# All validation rules pass
        todoss = form.save(commit=False)
        todoss.created_by = request.user
        form.save()
        return HttpResponseRedirect('/profile/')
else:
    form = formtodos() # An unbound form

context = {'form':form}
return render_to_response('todo.html', context,    context_instance=RequestContext(request))
4

1 回答 1

1

您已exclude = ('user',)在表单中指定。这意味着当您尝试保存表单时,没有user_id导致错误的存在。你可能想在通话之前把这个save()todoss.user = request.user

于 2012-10-14T10:28:58.293 回答