0

I have a DetailView, in which I show contents of a post and as well I wanted to add comments functionality to that view. I found 2 ways to do it: combine a DetailView and FormView or make a custom view with mixins. Since I am new to Djanfgo, I went on the 1st way, guided by this answer: Django combine DetailView and FormView but i have only a submit button and no fields to fill on a page. Here is a necessary code:

#urls.py
from . import views
app_name = 'bankofideas'
urlpatterns = [
    path('<int:pk>/', views.DetailView.as_view(), name='idea'),
    path('<int:idea_id>/vote', views.vote, name='vote'),
    path('<formview', views.MyFormView.as_view(), name='myform')

]

#views.py
class DetailView(generic.DetailView):
    model = Idea
    template_name = 'bankofideas/detail.html'
    context_object_name = 'latest_question_list'

    def get_queryset(self):
        return Idea.objects.filter(pub_date__lte=timezone.now())

    def get_context_data(self, **kwargs):  # передача формы
        context = super(DetailView, self).get_context_data(**kwargs)
        context['comment_form'] = CommentForm#(initial={'post': 
        self.object.pk})
        return context



class MyFormView(generic.FormView):
    template_name = 'bankofideas/detail.html'
    form_class = CommentForm
    success_url = 'bankofideas:home'


    def get_success_url(self):
         post = self.request.POST['post']
         Comment.objects.create()
         return '/'


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

#models.py
class Idea(models.Model):
    main_text = models.CharField(max_length=9001, default='')
    likes = models.IntegerField(default=0)
    pub_date = models.DateTimeField('date published', 
    default=timezone.now)

    def __str__(self):
        return self.main_text

    def save(self, *args, **kwargs):
        ''' On save, update timestamps '''
        if not self.id:
            self.pub_date = timezone.now()
        #self.modified = timezone.now()
        return super(Idea, self).save(*args, **kwargs)


class Comment(models.Model):
    post = models.ForeignKey(Idea, on_delete=models.PROTECT) # 
    related_name='comments',
    user = models.CharField(max_length=250)
    body = models.TextField(default=' ')
    created = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return self.body

    def get_absolute_url(self):
        return reverse('post_detail', args=[self.post.pk])


#forms.py
from .models import Idea, Comment
from django import forms


class IdeaForm(forms.ModelForm):
    class Meta:
        model = Idea
        fields = ('main_text',)


class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        exclude = ['post', 'datetime']

#detail.html
{% extends 'base.html' %}
{% load  bootstrap3 %}
{% block body %}
    <div class="container">
        <p>{{ idea.main_text }}   {{ idea.likes }} like(s)</p>

        {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
        <form action="{% url 'bankofideas:vote' idea.id %}" method="post">
            {% csrf_token %}
            <input type="submit" name="likes" id="idea.id" value="{{ idea.likes }}" />
        </form>
        {% for comment in idea.comment_set.all %}
            <p>{{comment.body}}</p>
        {% empty %}
            <p>No comments</p>
        {% endfor %}

        <form action="{% url "bankofideas:myform" %}" method="post">
            {% csrf_token %}
            {{ myform. }}
            <input type='submit' value="Отправить" class="btn btn-default"/>
        </form>

    </div>
{% endblock %}

As a result, I have an ability to see post, read all comments, like it, but cannot leave a comment. I tried to rename the form both in view and template, but it didn't work.

The question is: What should i do to bring comment form on the page?

Anthon
  • 1
  • 1
  • Please check the code you have posted closely - you currently have a comment `#` right after `CommentForm` in the detail view (`CommentForm#(initial={'post': `), which would cause the problem you are describing. – solarissmoke Apr 22 '18 at 02:54
  • I don't understand what you mean about "combining" the views. You haven't combined anything; you have two completely separate views here. – Daniel Roseman Apr 22 '18 at 08:29
  • (CommentForm#(initial={'post': ) doesn't wark regardless of that comment – Anthon Apr 22 '18 at 14:39

0 Answers0