Relating models in Django, ie Primary key to Foreign Key

From TRCCompSci - AQA Computer Science
Jump to: navigation, search

To complete this tutorial, you must have created a Product model in the previous tutorials.

models.py

Within your app folder, find the 'models.py' file and edit it, It should already contain a model for 'Product'. Firstly, we are going to have 'User' as one of the foreign keys so we must import the built in 'User' model:

from django.contrib.auth.models import User
from django.core.validators import MaxValueValidator, MinValueValidator
from django.utils import timezone

The other imports will allow validation of numerical fields, and to also get the current time. Now for the model itself, enter the following:

class Review(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    rating = models.IntegerField(validators = [MinValueValidator(0), MaxValueValidator(10)])
    text = models.TextField()
    date = models.DateTimeField( default=timezone.now )

    def __str__(self):
        return self.author.username + ' - ' + self.product.name + ' - ' + str(self.rating) + ' out of 10'

Register the Model

Now in the same folder as the 'models.py' find the 'admin.py'. It should currently have this code:

from django.contrib import admin
from .models import Product

admin.site.register(Product)

We now need to register the 'Review' model, so alter the code to this:

from django.contrib import admin
from .models import Product, Review

admin.site.register(Product)
admin.site.register(Review)

Now using the admin program, you will need to run the manage, and then makemigrations. You will then need to do the same and this time run migrate.

Checking your model

run the server and visit http:\\127.0.0.1:8000 and you should see your web app. In the address bar add '/admin' and login. You should see you model listed on the dashboard. You should be able to create new entries from this admin dashboard.

The Form

You will need to import your model into the 'forms.py':

from .models import Product

Your django form should be able to use the 'ModelChoiceField' component. You need to create a queryset from your model, for example:

product = forms.ModelChoiceField(queryset=Product.objects.all(), empty_label="Please Select")

We should not include the user/author field because if we did it could be changed in the form.

The View

When you process the form, the form will be valid but still fail to save. This is because we missed out the user/author field.

So in the views.py and the method to process the review you need to add the following to the 'if form.is_valid':

if form.is_valid:
    temp = form.save(commit=False)
    temp.user = request.user
    temp.save()
    messages.success(request, f'Your post has been successfully edited')
    return redirect('/')