D_P
D_P

Reputation: 862

Session key error while updating the page counts?

Here I am updating the page count in the homepage view but this code is not working properly.

It gives the IntegrityError saying NOT NULL constraint failed: mysite_pagevisit.session

What might be the reason? How can I solve it ?

class HomePageView(View):
    def get(self, request):
        if not PageVisit.objects.filter(session=request.session.session_key):
            PageVisit.objects.create(ip=request.META['REMOTE_ADDR'], session=request.session.session_key)

settings

SESSION_COOKIE_AGE = 5  #for test

models

class PageVisit(models.Model):
    ip = models.GenericIPAddressField()
    session = models.CharField(max_length=255)
    created = models.DateTimeField(auto_now_add=True)

    @property
    def total_visits(self):
        return PageVisit.objects.count()

Upvotes: 0

Views: 143

Answers (1)

ruddra
ruddra

Reputation: 51978

Your session key is None here. So you need to create one first if it is None. For example:

class HomePageView(View):
    def get(self, request):
        if not request.session.session_key:
            request.session.create()
        
        if not PageVisit.objects.filter(session=request.session.session_key):

Upvotes: 2

Related Questions