从两个不同的模型形成

时间:2014-02-24 20:24:23

标签: python django forms models

我需要从多个模型创建一个联系表单,如下所示:

class Customer(models.Model):
    name = models.CharField(max_length=128)
    email = models.EmailField(max_length=254, primary_key=True)
    phone_number = models.CharField(max_length=16, blank=True)

    def __unicode__(self):
        return self.name

class Customer_messages(models.Model):
    email = models.ForeignKey(Customer)
    message = models.TextField()

    def __unicode__(self):
        return self.email

我的问题是我需要从两个模型创建一个表格,其中应该有姓名,电子邮件,电话号码和消息。您可以看到模型通过电子邮件地址连接,这也是主键。你能帮我解决这个问题吗?

目前我的表单看起来像这样:

class CustomerContactFrom(forms.ModelForm):
name = forms.CharField(max_length=128, help_text="Meno: ")
email = forms.EmailField(max_length=254, help_text="Email: ")
phone_number = forms.CharField(max_length=16, help_text='Telefónne číslo: ')

class Meta:
    model = Customer

但如何为邮件添加下一个textarea并在发布时将其保存到DB?

感谢。

1 个答案:

答案 0 :(得分:0)

class CustomerContactFrom(forms.ModelForm):
    message = forms.CharField(widget=forms.widgets.Textarea())

    class Meta:
        model = Customer
        fields = ('name', 'email', 'phone_number')

    def save(self, *args, **kwargs):
        instance = super(CustomerContactFrom, self).save(*args, **kwargs)
        new_message = Customer_messages.objects.create(email=instance,
                                   message=self.cleaned_data['message'])

        return instance

此表格可以胜任。

建议:Customer_messages应该CustomerMessage', Camel-case writing and not plural.field of客户邮件model should be客户提供电子邮件,因为它是对客户的反对意见。这些只是建议:)