简体   繁体   English

Comment() 得到了一个意外的关键字参数“初始”

[英]Comment() got an unexpected keyword argument 'initial'

I am creating a Django blog and when trying to implement a comment system I got the above error.我正在创建一个 Django 博客,在尝试实现评论系统时出现上述错误。 I am not really sure what caused the problems, but I'll describe some of the things I did before I got the error.我不确定是什么导致了这些问题,但我会描述一些我在收到错误之前所做的事情。

I decided to use Django's class-based views to display all of my data.我决定使用 Django 的基于类的视图来显示我的所有数据。 In the PostDetailView shown I tried making it inherit from both DetailView and FormView so I get both the detail and form view displayed.在显示的 PostDetailView 中,我尝试让它从 DetailView 和 FormView 继承,以便同时显示详细信息和表单视图。

The commented-out code is code that I was going to use for the form view but I didn't know how to make it share the same template and URL route.注释掉的代码是我将用于表单视图的代码,但我不知道如何让它共享相同的模板和 URL 路由。

Views.py视图.py

from django.views.generic import DetailView, FormView
from .forms import Comment
from .models import Post

class PostDetailView(DetailView, FormView):
    model = Post
    template_name= 'optionhouseapp/post-detail.html'
    form_class = Comment

    def form_valid(self, form):
        return super().form_valid(form)

# class CommentFormView(FormView):
#     template_name= 'optionhouseapp/post-detail.html'
#     form_class = Comment
#     success_url ='/'

#     def form_valid(self, form):
#         return super().form_valid(form)

Here is the form page这是表格页面

forms.py forms.py

from django import forms 
from .models import Comment

class CommentForms(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ('name', 'email', 'body')

Here is the associated model这是相关的 model

models.py模型.py

class Comment(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments')
    name = models.CharField(max_length=80)
    email = models.EmailField()
    body = models.TextField()
    created_on = models.DateTimeField(auto_now_add=True)
    active = models.BooleanField(default=False)

    class Meta:
        ordering = ['created_on']

    def __str__(self):
        return "Comment {} by {}".format(self.body, self.name)

Here are the URLs这是网址

urls.py网址.py

from django.urls import path, include
from . import views

urlpatterns = [
    path('', views.IndexListView.as_view(), name='index'),
    path('postlist/', views.PostListView.as_view(), name='post-list' ),
    path('about/', views.about, name='about'),
    path('post/<int:pk>/', views.PostDetailView.as_view(), name='post-detail'),
    path('post-create', views.CreatePostView.as_view(), name='post_form'),
    path('post/<int:pk>/update', views.UpdatePostView.as_view(), name='post-update' ),
    path('post/<int:pk>/delete', views.DeletePostView.as_view(), name='post-delete')

]

Here is the HTML I am trying to display这是我要显示的 HTML

post-detail.html后细节。html

{%extends 'optionhouseapp/base.html'%}
{% load crispy_forms_tags %}

{%block content%}

    <div class='container'>
        {{object.image}} <br>
        {{object.title}} <br>
        {{object.author}} <br>
        {{object.date}} <br>
        {{object.content}} <br>
    </div>

    <div class='container'>
        {% if user.is_authenticated and user == object.author %}
            <a href="{% url 'post-update' post.id %}">Update</a>
            <a href="{% url 'post-delete' post.id %}">Delete</a>
        {% endif %}
    </div>

    <div class="container">
        <form method="POST">
            {% csrf_token %}
            <legend></legend>
            {{form | crispy}}
            <input type="submit" value="Submit">
        </form>
    </div>

{%endblock content%}

Here is the error that I am getting这是我得到的错误

Traceback (most recent call last):
  File "/Users/kevinhudgens/Developer/Environments/OptionHouse/env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/Users/kevinhudgens/Developer/Environments/OptionHouse/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/kevinhudgens/Developer/Environments/OptionHouse/env/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view
    return self.dispatch(request, *args, **kwargs)
  File "/Users/kevinhudgens/Developer/Environments/OptionHouse/env/lib/python3.8/site-packages/django/views/generic/base.py", line 98, in dispatch
    return handler(request, *args, **kwargs)
  File "/Users/kevinhudgens/Developer/Environments/OptionHouse/env/lib/python3.8/site-packages/django/views/generic/detail.py", line 107, in get
    context = self.get_context_data(object=self.object)
  File "/Users/kevinhudgens/Developer/Environments/OptionHouse/env/lib/python3.8/site-packages/django/views/generic/detail.py", line 100, in get_context_data
    return super().get_context_data(**context)
  File "/Users/kevinhudgens/Developer/Environments/OptionHouse/env/lib/python3.8/site-packages/django/views/generic/edit.py", line 66, in get_context_data
    kwargs['form'] = self.get_form()
  File "/Users/kevinhudgens/Developer/Environments/OptionHouse/env/lib/python3.8/site-packages/django/views/generic/edit.py", line 33, in get_form
    return form_class(**self.get_form_kwargs())
  File "/Users/kevinhudgens/Developer/Environments/OptionHouse/env/lib/python3.8/site-packages/django/db/models/base.py", line 501, in __init__
    raise TypeError("%s() got an unexpected keyword argument '%s'" % (cls.__name__, kwarg))
TypeError: Comment() got an unexpected keyword argument 'initial'
[26/Dec/2020 04:51:31] "GET /post/6/ HTTP/1.1" 500 89557

Please any help I can get on this would be truly appreciated.请任何我能得到的帮助将不胜感激。

You have defined your Form as CommentForm but in the DetailView you are using the form_class = Comment .您已将 Form 定义为CommentForm但在 DetailView 中您使用的是form_class = Comment You are importing .forms import Comment , instead you should use您正在导入.forms import Comment ,而是应该使用

.forms import CommentForm 
....
...
 form_class = CommentForm

Classbased Views could be tricky while using forms, I would suggest using function-based views when dealing with forms and other complex stuff.使用 forms 时,基于类的视图可能会很棘手,我建议在处理 forms 和其他复杂的东西时使用基于函数的视图。

from .forms import CommentForm
from .models import Post

def PostDetailView(request, slug):
    form = CommentForm()
    post = Post.objects.filter(slug=slug).first()


    comments = post.comments.all()

    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.post = post
            comment.save()
            form = CommentForm()

            context ={'post':post,'form':form,'comments':comments}
            return redirect('post-detail',slug=post.slug)

    context ={'post':post,'form':form,'comments':comments}
    return render(request,'blog/post_detail.html', context)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM