A
A
Alexander Goncharov2015-07-06 17:34:51
Django
Alexander Goncharov, 2015-07-06 17:34:51

Working with user data | Comments for an article?

Hello. I'm trying to make comments for articles, but when I enter the form and click on the Send comment button, the link 127.0.0.1:8000/articles/addcomment/1 opens and the comment is not added, although the comment should be added and the page of the article on which the comment of the form 127.0 was left opens. 0.1:8000/articles/get/1 .
URLs.py:

url(r'^articles/addcomment/(?P<article_id>\d)/+$', 'article.views.addcomment'),

The form itself in the html page:
<form action = '/articles/addcomment/{{ article.id }}/' method="post">
{% csrf_token %}
{{ form }}
<input type = 'submit' class = 'button' value="Добавить комментарий">
</form>

in models.py class:
class Comments(models.Model):
    class Meta:
        db_table = 'comments'
    text = models.TextField(verbose_name='Текст комметария')
    comments_article = models.ForeignKey(Article)

forms.py:
from django.forms import ModelForm
from article.models import Comments

class CommentForm(ModelForm):
    class Meta:
        model = Comments
        fields = '__all__'
        exclude = ['comments_article']

views.py
def addcomment(request, article_id):
    if request.POST:
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.comments_article = Article.objects.get(id=article_id)
            form.save()
    return redirect('/articles/get/%s/' % article_id)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
sim3x, 2015-07-06
@GoncharovAlex

Do not consider yourself smarter than developers - this function is needed if you inherited a database

class Meta:
        db_table = 'comments'

try not to use exclude
def addcomment(request, article_id):
    form = CommentForm(request.POST or None )
    if form.is_valid():
        comment = form.save(commit=False)
        comment.comments_article = Article.objects.get(id=article_id)
        form.save()
        # почитай reverse
        return redirect('/articles/get/%s/' % article_id)
    return render(request, 'template.html', {'form': form})

I advise you not to learn from this manu

V
Vov Vov, 2015-07-06
@balamut108

Hi there is a blog implementation with comments on the shadrus YouTube channel. You can take the implementation from there.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question