Django传递外键来查看

时间:2015-01-26 20:06:05

标签: python django forms model

嗨也许有人可以指出我正确的方向,我正在通过Tango与Django学习Django,我也跟随官方的Django教程,以及为购买订单创建我自己的Django应用程序。

我需要了解如何访问另一个模型的外键详细信息并使用表单保存。基本上我的应用程序在创建订单时有订单和供应商我可以让供应商外键选项显示在表单上但是当我保存它时我还想用suppier_name保存到订单表中,目前它只是保存supplier_id,我搜索了很多不同场景的例子,但感谢不能理解。

view.py

def add_order(request):
    if request.method == 'POST':
        form = OrderForm(request.POST)
        if form.is_valid():
            form.save(commit=True)
            return orders(request)
        else:
            print(form.errors)
    else:
        form = OrderForm()

    context_dict = {'form':form}

    return render(
        request,
        'purchaseorders/add_order.html',
        context_dict
    )

model.py

# Create your models here.

class Supplier(models.Model):
    supplier_code = models.CharField(max_length=10)
    supplier_name = models.CharField(
        max_length=100,
        unique=True
    )
    supplier_email = models.EmailField(max_length=100)
    supplier_website = models.URLField(max_length=100)
    slug = models.SlugField(unique=True)

    def save(self, *args, **kwargs):
        self.slug = slugify(self.supplier_name)
        super(Supplier,self).save(*args, **kwargs)

    def __unicode__(self):
        return self.supplier_name

    def __str__(self):
        return self.supplier_name

    class Meta:
        verbose_name_plural = "Suppliers"


class Order(models.Model):
    supplier = models.ForeignKey(Supplier)
    po_number = models.IntegerField(default=0)
    ordered_by = models.CharField(max_length=50)
    order_date = models.DateTimeField()
    supplier_name = models.CharField(max_length=50)
    net_value = models.DecimalField(
        decimal_places=2,
        max_digits=10
    )

    class Meta:
        verbose_name_plural = "Orders"

    def __unicode__(self):
        return self.po_number

forms.py

from django import forms
from PurchaseOrders.models import Supplier, Order

class SupplierForm(forms.ModelForm):
    supplier_code = forms.CharField(
        max_length=10,
        help_text="Please enter a unique code"
    )
    supplier_name = forms.CharField(
        max_length=100,
        help_text="Please enter the Suppliers full name"
    )
    supplier_email = forms.EmailField(
        max_length=100,
        help_text="Please enter a email address"
    )
    supplier_website = forms.URLField(
        max_length=100,
        help_text="Please enter a website"
    )
    slug = forms.CharField(
        widget=forms.HiddenInput(),
        required=False
    )

# an inline class to provide additional information on the form
    class Meta:
        # provide an association between the ModelForm and model
        model = Supplier
        fields = (
            'supplier_code', 'supplier_name', 
            'supplier_email', 'supplier_website'
        )

class OrderForm(forms.ModelForm):
    #list all form details except the Foreignkey connection
    po_number = forms.IntegerField(
        help_text="please enter a PO Number"
    )
    ordered_by = forms.CharField(
        max_length=50,
        help_text="please enter your name"
    )
    order_date = forms.DateTimeField(
        help_text="please enter a date of order"
    )
    #supplier_name = forms.ModelChoiceField(
        queryset=Supplier.objects.all()
    )
    net_value = forms.DecimalField(
        decimal_places=2,
        max_digits=10,
        help_text="please enter a net amount"
    )

    class Meta:
        # provide an association between the ModelForm and model
        model = Order

HTML     

{% load staticfiles %} <!-- New line -->

<html>
    <head>
        <title>Purchase Orders</title>
    </head>

    <body>
    <img src="{% static "purchaseorders/images/po_icon.png" %}" 
    alt="PO icon" />
    <h1>Add a Order</h1>

    <form id="order_form" method="post" 
    action="/PurchaseOrders/add_order/{{ supplier }}">

        {% csrf_token %}
        {% for hidden in form.hidden_fields %}
            {{ hidden }}
        {% endfor %}
        <ul style="list-style-type:none ">
        {% for field in form.visible_fields %}
            <li></li>
            {{ field.errors }}
            {{ field.help_text }}
            <li>{{ field }}</li>
        {% endfor %}
        </ul>
        <input type="submit" name="submit" value="Add Order" />
    </form>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

要从问题开始,您可以在模型的save()方法中捕获这些数据:

class Order(models.Model):
    [...]
    def save(self, *args, **kw):
        if self.supplier_id is not None:
            self.supplier_name = self.supplier.supplier_name
        super(Order, self).save(*args, **kw)

但是,尽管在某些情况下上述情况可能是正确的(例如,如果供应商名称预计会发生变化),通过现有关系简单地访问相关字段更为典型,例如:

myorder.supplier.supplier_name