Mohamed Abdillah
Mohamed Abdillah

Reputation: 395

How to write the view of saving a model which having foreign key

I am new in Django developing and I have a model Customers that is in a relationship with a ZipCode model. So from the model Customers, I want to get the zipCode in the ZipCode model. This, the ZipCode model has 4 attributes such as pk which is an aut_increment, zipCode which is unique, city and state. Therefore, my issues are: How to get the zipCode attribute as a foreign key in the Customer model and how the view of saving the customer object can be written? Below is are the Customers and the ZipCode models:

class Customers(models.Model):
    customerID = models.CharField(max_length=15, unique=True)
    firstName = models.CharField(max_length=20)
    lastName = models.CharField(max_length=25)
    phoneNumber = models.CharField(max_length=14)
    zipCode = models.ForeignKey(ZipCode, on_delete=models.CASCADE)
    address = models.TextField()

class ZipCode(models.Model):
    zipCode = models.CharField(max_length=10, unique=True)
    city = models.CharField(max_length=30)
    state = models.CharField(max_length=25)
    def __str__(self):
        return self.zipCode + ' ' + self.city + ' ' + self.state

Here also the view add_customers which is not working:

def add_Custmers(request):
    # try:
    #     zipCode=ZipCode.objects.get(slug=zipcode_slug)
    # except ZipCode.DoesNotExist:
    #     zipCode=None
    form=CustomersForm(request.POST or None)
    if form.is_valid():
        form.save()
    context = {'form': form}
    return render(request, 'customers.html', context

add customer form

I attached the add customer form for more details

class CustomersForm(forms.ModelForm):
    customerID = forms.CharField(max_length=15)
    firstName = forms.CharField(max_length=20)
    lastName = forms.CharField(max_length=25)
    phoneNumber = forms.CharField(max_length=14)
    zipCode = forms.ModelChoiceField(queryset=ZipCode.objects.all())
    address = forms.Textarea()
    class Meta:
        model=Customers
        fields=('customerID','firstName','lastName','phoneNumber', 'zipCode', 'address',)

Above is the form I define

Upvotes: 0

Views: 53

Answers (1)

Sulove Bista
Sulove Bista

Reputation: 118

Instead of saving the Form right after checking if it's valid or not, do this:

if form.is_valid():
    customer = form.save(commit=False)
    customer.zipCode = request.zipCode 
    form.save()

Let me know if it's still not working.

EDIT : Sorry didn't check it earlier. It should be request.POST['zipCode'] instead of request.zipCode

Upvotes: 2

Related Questions