Return outside function error eventhough it has been indented properly

Viewed 35

Hi I know this error is kind of silly but I am new to django. I also have indented the return function properly but it keeps on saying return outside function. I hope someone can help.

Trace back:

 File "C:\simpleblog\ablog\myblog\models.py", line 26
    return render(request, 'profile_page.html', {'pro':pro})
    ^
SyntaxError: 'return' outside function

models.py:

class UserProfileView(models.Model):
    user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
    bio = models.TextField()
    profile_pic = models.ImageField(null=True, blank=True, upload_to='images/profile/')
    website_url = models.CharField(max_length=255, null=True, blank=True)
    facebook_url = models.CharField(max_length=255, null=True, blank=True)
    pinterest_utl = models.CharField(max_length=255, null=True, blank=True)
    instagram_url = models.CharField(max_length=255, null=True, blank=True)
    twitter_url = models.CharField(max_length=255, null=True, blank=True)
    return render(request, 'profile_page.html', {'pro':pro})
    
    def __str__(self):
        return str(self.user)
1 Answers

The return render(request, 'profile_page.html', {'pro': pro}) does not make much sense. A model is request unaware, and furthermore should not render any pages, that is what the views are for.

You can return the URL where you can find the page for the UserProfile by implementing the .get_absolute_url() method [Django-doc]:

class UserProfile(models.Model):
    # …
    
    def get_absolute_url(self):
        return reverse('name-of-some-view', kwargs={'pk': self.pk})

In a view you can then decide how to render a page, but you are mixing models and views, and this is not how Django's architecture works: in the model.py you define models that focus on how to store data in the database.

In the views.py, you make handlers that, for a HTTP request, will construct a HTTP response, and these can make use of the models to obtain and render data.

A view is thus a function that has a request (and URL parameters) as input, and turns this into a HTTP output. One can also implement class-based views, but the .as_view(…) method [Django-doc] turns this into a function that handles HTTP requests and returns HTTP responses.

Related