无法从modelform自动选择外键

时间:2016-02-12 10:48:39

标签: python django django-1.7 modelform

我正在使用Python 2.7 / Django 1.7上的产品应用程序。

我有一个产品型号,即'product_profile',我想让我的客户(最终用户)使用表格询问有关特定产品的任何事情。

但是我无法允许用户自动选择产品(外键),客户必须从下拉菜单中进行选择,这是非常不合理的。我还在url-variable中分配了外键。

这是我的代码:

MODEL.PY

class ProductProfile(models.Model):
    category = models.ForeignKey(Category)
    brand = models.ForeignKey(Brand)
    product_name = models.CharField(max_length=128)
    model_name = models.CharField(max_length=128)
    generation = models.CharField(max_length=128)
    processor = models.CharField(max_length=128)
    ram = models.DecimalField(max_digits=2, decimal_places=0)
    hdd = models.DecimalField(max_digits=6, decimal_places=2)
    optical_drive = models.CharField(max_length=128)
    display = models.CharField(max_length=128)
    card_reader = models.CharField(max_length=128)
    blue_tooth = models.CharField(max_length=128)
    web_cam = models.CharField(max_length=128)
    warranty = models.CharField(max_length=128)
    price = models.DecimalField(max_digits=9, decimal_places=2)
    condition = models.TextField()
    product_image = models.ImageField(upload_to=update_Product_image_filename)
    post_date = models.DateTimeField(db_index=True, auto_now_add=True)

    # Override th __unicode__() method to return out something meaningful!
    def __unicode__(self):
        return self.product_name


class Customer_ps_contact(models.Model):
    name = models.CharField(max_length=128)
    email = models.EmailField(max_length=75)
    subject = models.CharField(max_length=128 )
    product = models.ForeignKey(ProductProfile)
    message = models.TextField()
    phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: 

'+999999999'. Up to 15 digits allowed.")
    phone_number = models.CharField(validators=[phone_regex], blank=True, max_length=15) # validators should be a 

list

    def __unicode__(self):
        return self.name

FORM.PY

class Customer_ps_contactForm(forms.ModelForm):

    class Meta:
        model = Customer_ps_contact
        product = forms.ModelChoiceField(queryset=ProductProfile.objects.all(),
widget=forms.HiddenInput())

        fields = ('name','email', 'product','subject','message', 'phone_number')

VIEWS.PY

def product_inquiry(request, product_id):
    product = ProductProfile.objects.get(pk=product_id)
    if request.method == 'POST':
        #form = Customer_ps_contactForm(request.POST, initial = {'product': product})

        #form = Customer_ps_contactForm(initial = {'product': product.id})

        form = Customer_ps_contactForm(request.POST)

        if form.is_valid():

            form_data_dict = form.cleaned_data
            print form_data_dict['product']
            mail_customer_enquriy(form_data_dict) # Function to send email to admin
            thank_u_customer(form_data_dict) # Function to send email to customers

            form = form.save(commit=False)
            form.product = product
            form.save()
            return home(request)
        else:
            print ("form is not valid")
            print (form.errors)
    else:
        form = Customer_ps_contactForm()

    context_dict = {'form':form, 'product': product}

    return render(request, 'product/product_inquiry2.html',context_dict)

网址格式

urlpatterns = patterns('',
       url(r'^inquiry/(?P<product_id>\d+)/$', views.product_inquiry, name='price'), # Only relevent url given
       ) 

模板:product_inquiry2.html

{% extends 'base.html' %}
{% load crispy_forms_tags %}


{% block body_block %}
{% block title %}Product Inquiry{% endblock %}

<div class="row">
    <div class="col-md-10 col-md-offset-1">
        <h2 style="font-weight:bold">Enquiry regarding '{{product.product_name}}'</h2>
        <hr>
        <form id="contact_form" method="post" action=""/>

            {% csrf_token %}
            {{ form | crispy }}

            <input class="btn btn-primary pull-right " type="submit" name="submit" value="Submit the Message" />
        </form>

    </div>
</div>





{% endblock %}

我该怎么办?

1 个答案:

答案 0 :(得分:2)

您知道该产品来自网址中的ID,因此无需在表单中包含该产品。

要检查数据库中是否存在该产品,您可以使用get_object_or_404快捷方式。

def product_inquiry(request, product_id):
    product = get_object_or_404(ProductProfile, pk=product_id)

然后从字段列表中省略“产品”,并删除带有隐藏输入窗口小部件的ModelChoiceField

class Customer_ps_contactForm(forms.ModelForm):

    class Meta:
        model = Customer_ps_contact

        fields = ('name','email','subject','message','phone_number')

您在保存时已经设置了产品,但使用变量名instance可以更清楚地了解正在发生的事情。如果您更改mail_customer_enquriythank_u_customer方法以使用实例而不是cleaned_data,则您无需对form.cleaned_data执行任何操作。

    if form.is_valid():
        instance = form.save(commit=False)
        instance.product = product
        instance.save()

        mail_customer_enquriy(instance) # Function to send email to admin
        thank_u_customer(instance) # Function to send email to customers

        return home(request)