我对如何将附加表单附加到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))
答案 0 :(得分:1)
您已在表单中指定exclude = ('user',)
。这意味着当您尝试保存表单时,不会出现user_id
,从而导致错误。您可能希望在save()
来电之前提出此问题:todoss.user = request.user