django 如何在视图中设置外键字段?

jutyujz0  于 2022-12-01  发布在  Go
关注(0)|答案(2)|浏览(202)

我尝试在测试模型上保存customer字段,没有收到任何错误,但也没有保存字段,如何修复?
型号

class Test(models.Model):
    customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True)
    email = models.EmailField(max_length=200, blank=False)

表格

class TestForm(forms.Form):
    email = forms.EmailField(required=True)

    class Meta:
        model = Test
        fields = ("email")

    def save(self, commit=False):
            # Creating the customer object
            Test.objects.create(email=self.cleaned_data['email'])

查看次数

def test_view(request):
    customer = request.user.customer

    if form.is_valid():
        email = form.cleaned_data['email']
        customer = customer
        form.save()
zujrkrfu

zujrkrfu1#

您可以使用cleaned_data来储存ModelForm。
forms.py

class TestForm(forms.ModelForm):

    class Meta:
        model = Test
        fields = ["email"]

假设您有请求方法POST
views.py

def test_view(request):
    if request.method=="POST":
        form=TestForm(request.POST)
 
        customer = request.user.customer

        if form.is_valid():
            email = form.cleaned_data['email']
            test=Test(customer=customer,email=email)
            test.save()
tct7dpnv

tct7dpnv2#

您需要使用ModelForm,然后保存对象而不提交,编辑对象的客户,然后提交。
第一个

相关问题