问题描述:

Getting Error "Todos.user" must be a "UserProfile" instance. can someone explain why?

I want users in Todos should point to UserProfile and whatever I save in Todos should be displayed in /profile/ ?

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(UserProfile)

title = models.CharField(max_length=100)

created = models.DateField()

start_time = models.TimeField()

end_time = models.TimeField()

def __unicode__(self):

return unicode(self.user)

Form

class todosform(ModelForm):

title = forms.CharField(label=(u'Todo'))

created = forms.DateField(label=(u'Date'))

start_time = forms.TimeField(label=(u'Start Time'))

end_time = forms.TimeField(label=(u'End Time'))

#user = forms.CharField(label=(u'username')

class Meta:

model = Todos

exclude=('user',)

#url todo url(r'^todo/$', 'registration.views.todo'),

def todo(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.user = request.user

form.save()

return HttpResponseRedirect('/profile/')

else:

form = formtodos()

context = {'form':form}

return render_to_response('todo.html', context, context_instance=RequestContext(request))

#url profile url(r'^profile/$', 'registration.views.Profile'),

@login_required # decorator to check if request login

def Profile(request):

if not request.user.is_authenticated(): #if user not logged in

return HttpResponseRedirect('/login/')

#model = request.user.todos_set.all().order_by('created')[:7]

#u = Todos.objects.filter(created_by = request.user).get(pk=user)

registration = request.user.get_profile

context = {'registration':registration }

return render_to_response('profile.html',context,context_instance=RequestContext(request))

网友答案:

Your user field on Todos is a ForeignKey to UserProfile, not User. request.user is an instance of User. You could to this:

todoss.user = request.user.get_profile()
相关阅读:
Top