我正在尝试建立一个用户个人资料页面,用户可以在其中管理他们订阅的“客户”。出于测试目的,我在模板中调用整个表单{{customer_subscription}},它正在返回用户的正确实例,但我希望它还可以在表单实例上突出显示该用户的订阅“客户”但它没有选择任何东西。我做错了什么?
models.py
class UserProfile(models.Model):
user = models.OneToOneField(User)
phone = models.CharField(max_length=10, blank=True)
def __unicode__(self):
return self.user.username
class Customers(models.Model):
customer = models.CharField(max_length=200)
def __unicode__(self):
return self.customer
class Customer_Subscription(models.Model):
user = models.ForeignKey(User)
customers = models.ManyToManyField('Customers')
def __unicode__(self):
return (self.user)
forms.py
class CustomerSubscriptionForm(forms.ModelForm):
class Meta:
model = Customer_Subscription
fields = '__all__'
views.py
def profile(request):
userprofile = UserProfile.objects.get(user=request.user)
customer_subscription = CustomerSubscriptionForm(instance=userprofile)
return render_to_response('profile.html', {'userprofile' : userprofile, 'customer_subscription':customer_subscription, },context_instance=RequestContext(request))
答案 0 :(得分:1)
创建ModelForm时,必须使用CustomerSubscription对象实例而不是UserProfile
def profile(request):
userprofile = UserProfile.objects.get(user=request.user)
customer_subs = CustomerSubscription.objects.get(user=userprofile)
customer_subscription = CustomerSubscriptionForm(instance=customer_subs)
return render_to_response('profile.html', {'customer_subscription' : customer_subscription, 'customer_subscription':customer_subscription, },context_instance=RequestContext(request))