即使已正确缩进,也返回外部函数错误

时间:2021-07-10 11:35:05

标签: django

嗨,我知道这个错误有点傻,但我是 Django 的新手。我也正确缩进了返回函数,但它一直说返回函数外。希望有人能帮忙。

追溯:

 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 个答案:

答案 0 :(得分:0)

return render(request, 'profile_page.html', {'pro': pro}) 没有多大意义。模型不知道请求,而且应该呈现任何页面,这就是视图的用途。

您可以通过实现 .get_absolute_url() method [Django-doc] 返回可以找到 UserProfile 页面的 URL:

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

在视图中,您可以决定如何呈现页面,但是您混合了模型和视图,这不是 Django 架构的工作方式:在 model.py 中,您定义了专注于如何在数据库中存储数据。

views.py 中,您可以创建处理程序,这些处理程序将针对 HTTP 请求构建 HTTP 响应,并且这些处理程序可以使用模型来获取和呈现数据。

因此,视图是一个函数,它以请求(和 URL 参数)作为输入,并将其转换为 HTTP 输出。还可以实现基于类的视图,但 .as_view(…) method [Django-doc] 将其转换为处理 HTTP 请求并返回 HTTP 响应的函数。

相关问题