2012-08-06 82 views
1

我想創建一個將在大多數情況下都在客戶模型的字段的值相同客戶的發票,但有時一個或多個字段對發票改變。相對獲取初始數據選擇ForeignKey的在Django的ModelAdmin

爲了更好地理解這裏是模型的簡化版本:

class Customer(models.Model): 
    name = models.CharField(max_length=50) 
    surname = models.CharField(max_length=50) 
    email = models.Charfield(max_length=50) 

class Invoice(models.Model): 
    customer = models.ForeignKey(Customer) 
    name = models.CharField(max_length=50) 
    surname = models.CharField(max_length=50) 
    email = models.Charfield(max_length=50) 

我在客戶管理頁面一個特殊的按鈕,用戶/admin/sell/invoice/add/?customer=[customer.id]

什麼是最好的方式重定向使用Customer模型中的值預填充Invoice admin中的字段?發票模型admin具有可用的客戶ID。

回答

1

爲了能夠預填充您的管理視圖,您需要修改管理形式是這樣的:

class InvoiceForm(forms.ModelForm): 
    class Meta: 
     model = Invoice 

    def __init__(self, *args, **kwargs): 
     super(InvoiceForm, self).__init__(*args, **kwargs) 
     # get the customer ID somehow 
     my_customer = Customer.objects.get(id=CUSTOMER_ID) 
     self.initial['name'] = my_customer.name 
     self.initial['surname'] = my_customer.surname 
     self.initial['email'] = my_customer.email 


class InvoiceAdmin(admin.ModelAdmin): 
    form = InvoiceForm 
+0

謝謝,我用'kwargs得到了客戶ID [「初步」] [「客戶」]' – 2012-08-12 15:02:02

相關問題