[英]Django integrity error NOT NULL constraint
i'm creating a blog site which requires a login to write a post.As of now, ive just created the create post and update post views, but when i try to submit a created post, this integrity error is raised.我正在创建一个需要登录才能写帖子的博客站点。截至目前,我刚刚创建了创建帖子并更新了帖子视图,但是当我尝试提交创建的帖子时,会引发此完整性错误。 I dont know how to get through this.
我不知道如何度过这个难关。 Help is appreciated:) the error
帮助表示赞赏:)错误
VIEWS意见
class CreatePost(LoginRequiredMixin,CreateView):
form_class = forms.PostForm
template_name = "blog/create_post.html"
APP URLS应用网址
app_name = 'blog'
urlpatterns = [
path("login/",auth_view.LoginView.as_view(template_name="blog/login.html"), name='login'),
path("logout/",auth_view.LogoutView.as_view(), name="logout"),
path("signup/",views.SignUpView.as_view(), name="signup"),
path("new/",views.CreatePost.as_view(), name="newpost")
]
ROOT URLS根网址
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.HomePageView.as_view(), name = "home"),
path('logged/',views.LoggedPage.as_view(), name='logged'),
path('thanks',views.ThanksPage.as_view(), name='thanks'),
path('blog/',include("blog.urls", namespace='blog')),
path('blog/',include("django.contrib.auth.urls")),
]
In your CreatePost
, you should attach the logged in user to the post:在您的
CreatePost
中,您应该将登录用户附加到帖子中:
class CreatePost(LoginRequiredMixin, CreateView):
form_class = forms.PostForm
template_name = 'blog/create_post.html'
def form_valid(self, form):
form
.instance.user = request.user
return super().form_valid(form)
You should also specify a success_url
[Django-doc] , or a get_success_url
[Django-doc] to specify to what view you redirect in case of a succesful POST request.您还应该指定一个 success_url [Django-doc
success_url
或一个get_success_url
[Django-doc]以指定在成功的 POST 请求的情况下重定向到哪个视图。 You can also implement the get_absolute_url
method [Django-doc] , to redirect to the details of that Post
object.您还可以实现
get_absolute_url
方法 [Django-doc] ,以重定向到该Post
object 的详细信息。
Note : It is normally better to make use of the
settings.AUTH_USER_MODEL
[Django-doc] to refer to the user model, than to use theUser
model [Django-doc] directly.注意:通常最好使用
settings.AUTH_USER_MODEL
[Django-doc]来引用用户 model,而不是直接使用User
model [Django-doc] 。 For more information you can see the referencing theUser
model section of the documentation .有关更多信息,您可以查看参考文档的
User
model部分。
Note : In Django, class-based views (CBV) often have a
…View
suffix, to avoid a clash with the model names.注意:在 Django 中,基于类的视图 (CBV) 通常有一个
…View
后缀,以避免与 model 名称发生冲突。 Therefore you might consider renaming the view class toCreatePostView
, instead of.CreatePost
因此,您可以考虑将视图 class 重命名为
CreatePostView
,而不是。CreatePost
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.