无法将外键对象保存到model.cc

时间:2016-05-13 09:32:54

标签: python-3.x django-models django-forms

我正在尝试保存视图中的数据,我的两个模型是:

models.py

    class Customer(models.Model) :
    name = models.CharField(max_length=25)
    address = models.CharField(max_length=250)
    phone_number = models.IntegerField()
    email = models.EmailField(max_length=35)
    contact_person = models.CharField(max_length=25)
    created_date = models.DateTimeField(auto_now_add=True, null=True)

    def __str__(self):
        return self.name

class Product(models.Model):
    support = models.CharField(max_length=8, choices=support_choice, null=True)
    amc_date = models.DateField(null=True)
    amc_product = models.CharField(max_length=500, default="No Products in amc")
    warranty_date = models.DateField(null=True)
    warranty_product_list = models.CharField(max_length=500, default="No Products in warranty")
    product_name = models.CharField(max_length=100, null=True)
    serial_number = models.CharField(max_length=50, null=True)
    customer = models.ForeignKey(Customer)

    def __str__(self):
        return self.product_name

我为产品创建了一个表单:

class ProductForm(forms.ModelForm):
support = forms.ChoiceField(choices=support_choice, required=True,)
amc_date = forms.DateField(required=False, widget=forms.TextInput(attrs={'placeholder': 'ex: 10/25/2006'}))
amc_product = forms.CharField(required=False, widget=forms.TextInput(attrs={'placeholder': 'Products listed in AMC'}))
warranty_date = forms.DateField(required=False, widget=forms.TextInput(attrs={'placeholder': 'ex: 10/25/2006'}))
warranty_product_list = forms.CharField(required=False, widget=forms.TextInput(attrs={'placeholder': 'Products listed in warranty'}))
product_name = forms.CharField(required=True, widget=forms.TextInput(attrs={'placeholder':'Product model'}))
serial_number = forms.CharField(required=True)

class Meta:
    model = Product
    fields = ['support', 'amc_date', 'amc_product', 'warranty_date', 'warranty_product_list', 'product_name',
              'serial_number']

在我的views.py中我试图将外键对象保存到产品数据库但是我收到错误"无法分配"' Sabaree'&# 34;:" Product.customer"必须是"客户" 。实例"

views.py

def product_detail(request):
cust = request.POST.get('customer_name')
obj = Customer.objects.all()
obj1 = obj.filter(name=cust)
print (cust)
if request.method == 'POST':
    form = ProductForm(request.POST)
    if form.is_valid():

        a = form.save(commit=False)
        a.customer = cust
        form.save()

context = {'obj':obj, 'form':form}
return render(request,"products.html",context)

我的模板是: products.html放在

 {% block content %}
<script type="text/javascript" src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<script src="{% static 'js/product_detail.js' %}"></script>
<div class="container">
    <h2>Products</h2>
   <form method="post" action="" enctype="multipart/form-data">
    {% csrf_token %}
    <div class="controls ">
    <select class="select form-control" id="id_customer_name" name="customer_name">
        {% for i in obj %}
            <option id="{{ i.id }}" value="{{ i.name }}">{{ i.name }}{{ i.id }}</option>
        {% endfor %}
    </select>
    </div>
    {{ form|crispy }}
    <input type="submit" class="btn btn-default " value="Submit">
</form>
</div>
{% endblock %}

我不确定如何保存在Product表中指定为外键的数据。

1 个答案:

答案 0 :(得分:0)

由于Customer是外键,因此您无法分配从POST方法获得的值。尝试其中任何一个

a.customer.name = cust

或者将其转换为Customer表对象,如下所示

cust_obj = Customer.objects.get(name=cust) # Assuming cust is unique or do a query to return obj
then while save,
 a.customer = cust