django登录userprofile并关联其他表单

时间:2012-10-14 10:11:26

标签: django django-models django-forms django-views

我对如何将附加表单附加到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))

1 个答案:

答案 0 :(得分:1)

您已在表单中指定exclude = ('user',)。这意味着当您尝试保存表单时,不会出现user_id,从而导致错误。您可能希望在save()来电之前提出此问题:todoss.user = request.user