【问题标题】:Django Form instance not workingDjango 表单实例不起作用
【发布时间】:2014-02-02 00:44:35
【问题描述】:

我正在尝试创建一个用户个人资料页面,用户可以在其中管理他们订阅的“客户”。出于测试目的,我在模板中调用了整个表单 {{ 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))

【问题讨论】:

  • 您已经为您的Customer_Subscription 模型创建了一个模型表单,因此instance 应该是一个Customer_Subscription 实例。相反,您传递的是用户配置文件,这没有意义。

标签: django forms models


【解决方案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))

【讨论】:

    猜你喜欢
    • 2015-12-28
    • 2015-12-03
    • 1970-01-01
    • 2015-04-16
    • 1970-01-01
    • 1970-01-01
    • 2017-10-03
    • 1970-01-01
    相关资源
    最近更新 更多