Django CreateView外键 [英] Django CreateView Foreign key

查看:84
本文介绍了Django CreateView外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一些帮助.我正在使用Django 2.1和python 3.7编写应用程序

I need some help. I'm writing an app with Django 2.1 and python 3.7

我正在尝试添加一个新注释,该注释通过外键与文章相关联.

I am trying to add a new Comment that it is associated to an Article through foreign key.

要添加新评论的屏幕网址为 http://127.0.0.1:8000/articles/1/comment/new/,因此该网址具有外键.

The url of the screen to add a new comment is http://127.0.0.1:8000/articles/1/comment/new/ so the url has the foreign key.

当我尝试保存评论时,它会返回以下错误:

When I try a save the comment it returns the error below:

IntegrityError at /articles/1/comment/new/
NOT NULL constraint failed: articles_comment.article_id
Request Method: POST
Request URL:    http://127.0.0.1:8000/articles/1/comment/new/
Django Version: 2.0.6
Exception Type: IntegrityError
Exception Value:    
NOT NULL constraint failed: articles_comment.article_id
Exception Location: /Users/fabiodesimoni/.local/share/virtualenvs/news-s2R6SLTq/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py in execute, line 303
Python Executable:  /Users/fabiodesimoni/.local/share/virtualenvs/news-s2R6SLTq/bin/python
Python Version: 3.7.1
Python Path:    
['/Users/fabiodesimoni/Development/Python/Django/news',
 '/Users/fabiodesimoni/.local/share/virtualenvs/news-s2R6SLTq/lib/python37.zip',
 '/Users/fabiodesimoni/.local/share/virtualenvs/news-s2R6SLTq/lib/python3.7',
 '/Users/fabiodesimoni/.local/share/virtualenvs/news-s2R6SLTq/lib/python3.7/lib-dynload',
 '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7',
 '/Users/fabiodesimoni/.local/share/virtualenvs/news-s2R6SLTq/lib/python3.7/site-packages']
Server time:    Tue, 18 Dec 2018 10:05:07 +0000

如果我将文章"字段添加到注释"屏幕中,则该屏幕上将显示文章"字段为空白,我必须选择文章"才能成功保存它.我想自动执行此操作,因为文章ID位于url中.

If I add the field Article into the Comment screen, the screen is loaded with the field Article blank and I am have to select the Article in order to save it with success. I want to do it automatically because the article id is in the url.

我希望所有信息都在这里,以防万一需要代码,源代码为 https://github.com/fabiofilz/newspaper_app

I hope all information are here and in case it needed the code the source code is https://github.com/fabiofilz/newspaper_app

Model.py:

    from django.contrib.auth.models import User
    from django.conf import settings
    from django.contrib.auth import get_user_model
    from django.db import models
    from django.urls import reverse

    class Article(models.Model):
        title = models.CharField(max_length=255)
        body = models.TextField()
        date = models.DateTimeField(auto_now_add=True)
        author = models.ForeignKey(get_user_model(),on_delete=models.CASCADE,)

        REQUIRED_FIELDS = ['author', 'title', 'body']

        def __str__(self):
            return '(id: ' + str(self.id) + ') ' + self.title

        def get_absolute_url(self):
            return reverse('article_detail', args=[str(self.id)])

    class Comment(models.Model):
        article = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='comments')
        comment = models.CharField(max_length=140)
        author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, )

        def __str__(self):
            return '(id: ' + str(self.id) + ') ' + self.comment

        def get_absolute_url(self):
            reverse('comment_detail', args=[str(self.id)])

url.py

urlpatterns = [
    path('', views.ArticleListView.as_view(), name='article_list'),
    path('<int:pk>/edit/', views.ArticleUpdateView.as_view(), name='article_edit'),
    path('<int:pk>/', views.ArticleDetailView.as_view(), name='article_detail'),
    path('<int:pk>/delete/', views.ArticleDeleteView.as_view(), name='article_delete'),
    path('new/', views.ArticleCreateView.as_view(), name='article_new'),

    path('<article_pk>/comment/<comment_pk>', views.CommentDetailView.as_view(), name='comment_detail'),
    url(r'^(?P<pk>\d+)/comment/(?P<comment_pk>\d+)/delete/$', views.CommentDeleteView.as_view(), name='comment_delete'),
    url(r'^(?P<pk>\d+)/comment/(?P<comment_pk>\d+)/edit/$', views.CommentUpdateView.as_view(), name='comment_edit'),
    path('<article_pk>/comment/new/', views.CommentCreateView.as_view(), name='comment_new'),
]

view.py

from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import ListView, DetailView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.urls import reverse_lazy
from . import models
from django.utils import timezone
from django.shortcuts import redirect

# COMMENT VIEWS

class CommentCreateView(LoginRequiredMixin, CreateView):
    model = models.Comment
    template_name = 'comment_new.html'
    fields = ['comment'] #, 'article']
    success_url = reverse_lazy('article_list')
    login_url = 'login'

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)

谢谢

推荐答案

我发现了类似的问题:

没有NULL约束失败的Django CreateView

class CommentCreateView(LoginRequiredMixin, CreateView):
    model = models.Comment
    template_name = 'comment_new.html'
    fields = ['comment'] #, 'article']
    success_url = reverse_lazy('article_list')
    login_url = 'login'

    def form_valid(self, form):
        form.instance.author = self.request.user
        form.instance.article = get_object_or_404(models.Article, 
                                                  id=self.kwargs.get('article_pk')) # new line
        return super().form_valid(form)

这篇关于Django CreateView外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆