使用django

时间:2018-01-27 15:08:52

标签: python django

我收到错误:

  

NOT NULL约束失败:films_comment.film_id

在评论页面上有一个名为body的表单字段用于评论本身,我还需要它来存储针对用户和电影的评论。

型号:

from django.db import models
from django.urls import reverse

class Film(models.Model):
    title = models.CharField(max_length=200)
    director = models.CharField(max_length=200)
    description = models.CharField(max_length=200)
    pub_date = models.DateField('date published')

    def get_absolute_url(self):
        return reverse('films:detail', kwargs={'pk' : self.pk})

class Comment(models.Model):
# user = models.ForeignKey(User, on_delete=models.CASCADE)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    film = models.ForeignKey(Film, on_delete=models.CASCADE)
    body = models.CharField(max_length=200)

查看:

from django.views import generic
from .models import Film, Comment
from django.views.generic.edit import CreateView, UpdateView, DeleteView

class IndexView(generic.ListView):
    # model = Film
    template_name = 'films/index.html'
    # context_object_name = 'object_list'

    def get_queryset(self):
        return Film.objects.all()

class DetailView(generic.DetailView):
    model = Film
    template_name = 'films/detail.html'


class CommentCreate(CreateView):
    model = Comment
    fields = ['body']

的url:

app_name = 'films'

urlpatterns = [
    path('', views.IndexView.as_view(), name='index'),
    # path('<int:film_id>/comment', views.add_comment, name='add_comment'),
    path('<int:pk>', views.DetailView.as_view(), name='detail'),
    path('<int:film_id>/comment/', views.CommentCreate.as_view(), name='add_comment'),
]

添加评论的详细信息页面上的链接:

<a href="{% url 'films:add_comment' film_id=film.id %}">Leave a comment</a>

comment_form.py:

<form action="" method="post">
    {% csrf_token %}
    {% include 'films/form-template.html' %}
    <button type="submit">Submit</button>
</form>

表单模板:

{% for field in form %}

{{field.errors}}

<label>{{ field.label_tag }}</label>
{{ field }}

{% endfor %}

forms.py

from django import forms
from .models import Comment

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ('body',)

1 个答案:

答案 0 :(得分:3)

您需要覆盖视图的form_valid方法,以使用当前用户和电影更新新的评论实例:

class CommentCreate(CreateView):
    model = Comment
    fields = ['body']

    def form_valid(self, form):
        film = Film.objects.get(pk=self.kwargs['film_id']) 
        form.instance.user = self.request.user         
        form.instance.film = film 
        return super(CommentCreate, self).form_valid(form)

修复&#34;没有网址重定向到&#34;您可以将get_absolute_url()方法添加到评论模型中:

def get_absolute_url(self):
    return reverse('detail', kwargs={'pk': self.film.pk})