无法从modelform自动选取外键

2024-05-04 00:24:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在开发python2.7/django1.7上的产品应用程序。在

我有一个产品模型,即“产品配置文件”,我想让我的客户(最终用户)用表格询问有关特定产品的任何事情。在

但是,我无法从用户选择的产品中选择一个非常不合理的键。我还分配了url变量中的外键。在

这是我的代码:

在模型.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

在表单.PY

^{pr2}$

在视图.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)

URL模式

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 %}

我该怎么办?在


Tags: tonameformreturn产品modelsrequestcustomer
1条回答
网友
1楼 · 发布于 2024-05-04 00:24:00

您可以从url中的id知道产品是什么,所以不需要在表单中包含它。在

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

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

然后从字段列表中去掉“product”,并删除带有隐藏输入小部件的ModelChoiceField。在

^{pr2}$

在保存产品时,您已经在设置产品,但是使用变量名instance可以更清楚地显示正在发生的事情。如果您更改mail_customer_enquriythank_u_customer方法来使用实例而不是{},那么您就不必对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)

相关问题 更多 >