【问题标题】:unable to save Foreign key object to the model.cc无法将外键对象保存到 model.cc
【发布时间】:2016-09-09 10:28:15
【问题描述】:

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

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'”:“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 %}

我不确定如何保存在产品表中分配为外键的数据。

【问题讨论】:

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


    【解决方案1】:

    由于 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
    

    【讨论】:

    • 我尝试使用您提到的方法,但我得到记录的 id 而不是名称,因为表单在 POST 中发送客户名称的 id 并将其保存在数据库中。 cust = request.POST.get('customer_name') cust_obj = Customer.objects.get(id=cust) a = Product(support=support1, amc_date=amc_date1, amc_product=amc_product1, warranty_date=warranty_date1, warranty_product_list=warranty_product_list1,product_name=product_name1, serial_number=serial_number1,customer=cust_obj) a.save() 感谢您给我一些指示。
    猜你喜欢
    • 1970-01-01
    • 2020-06-22
    • 2011-08-18
    • 2021-09-20
    • 1970-01-01
    • 2017-07-05
    • 2020-11-15
    • 2013-07-10
    • 2016-06-30
    相关资源
    最近更新 更多