Home > OS >  How to set a foreignkey field in views?
How to set a foreignkey field in views?

Time:11-28

I'm trying to save the customer field on the Test model, I'm not getting any errors but it's not saving the field either, how do I fix it?

Models

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)

Forms

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'])

Views

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

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

CodePudding user response:

You can use cleaned_data to save the ModelForm.

forms.py

class TestForm(forms.ModelForm):

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

Assuming, you have request method 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()

CodePudding user response:

You need to use a ModelForm, then save the object without commiting, edit the customer of the object, then commit.

class TestForm(forms.ModelForm):

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

def test_view(request):
    customer = request.user.customer #I'm not sure this line is right, but I can't see all your models

    if form.is_valid():
        test = form.save(commit=False)
        test.customer = customer
        test.save()
  • Related