0

Если быть точнее, нужно переписать рабочую функцию на класс DetailView или же предложить лучшую реализацию. И было бы здорово получить решение привязки Юзера к комментарию, так как в моем случае приходиться выбирать из всех существующих. Заранее спасибо!

Функция:

def product_detail(request, pk):
    template_name = 'main/product_detail.html'
    product = get_object_or_404(Product, pk=pk)
    comments = product.comments.filter(active=True)
    new_comment = None
    # Comment posted
    if request.method == 'POST':
        form = CommentForm(data=request.POST)
        if form.is_valid():

            # Create Comment object but don't save to database yet
            new_comment = form.save(commit=False)
            # Assign the current post to the comment
            new_comment.product = product
            # Save the comment to the database
            new_comment.save()
    else:
        form = CommentForm()

    return render(request, template_name, {'product': product,
                                           'comments': comments,
                                           'new_comment': new_comment,
                                           'form': form})

Модель:

class Comment(models.Model):
    product = models.ForeignKey(Product,on_delete=models.CASCADE,related_name='comments')
    username = models.ForeignKey(Profile, on_delete=models.CASCADE)
    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.username)

Форма:

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

Шаблон:

<!-- comments -->
        <h2>{{ comments.count }} comments</h2>
              <hr>
 {% for comment in comments %}
            <p>{{ comment.body | linebreaks }}</p>
            <small class="text-muted">Posted by <b>{{ comment.username }}</b> on {{ comment.created_on }}</small><br><br>
{% endfor %}
            <hr>


        {% if new_comment %}
        <div class="alert alert-success" role="alert">
          Your comment is awaiting moderation
        </div>
        {% else %}
        <h3>Leave a comment</h3>
        <form action="." method="post" style="margin-top: 1.3em;">
          {{ form.as_p }}
          {% csrf_token %}
          <button type="submit" class="btn btn-success">Leave a Review</button>
        </form>
        {% endif %}

1 ответ 1

1

Если я правильно понял, то привязать юзера к модели cледует так:

class Comment(models.Model):
user = models.ForeignKey(User,on_delete=models.CASCADE)

А потом перед тем как будешь сохранять форму:

 form.user = request.user
 form.save()

А по поводу переписать функцию на класс можешь взять этот пример.

class Detail(DetailView):
    model = MyModel
    template_name = 'mymodel_detail.html'

    def get_context_data(self, **kwargs):
        context = super(Detail, self).get_context_data(**kwargs)
        context['form'] = DetailForm
        return context

    def post(self, request, *args, **kwargs):
        form = DetailForm(request.POST, request.FILES)
        if form.is_valid():
            # Write Your Logic here

            self.object = self.get_object()
            context = super(Detail, self).get_context_data(**kwargs)
            context['form'] = DetailForm
            return self.render_to_response(context=context)

        else:
            self.object = self.get_object()
            context = super(Detail, self).get_context_data(**kwargs)
            context['form'] = form
            return self.render_to_response( context=context)
0

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.