Answer the question
In order to leave comments, you need to log in
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'),
<form action = '/articles/addcomment/{{ article.id }}/' method="post">
{% csrf_token %}
{{ form }}
<input type = 'submit' class = 'button' value="Добавить комментарий">
</form>
class Comments(models.Model):
class Meta:
db_table = 'comments'
text = models.TextField(verbose_name='Текст комметария')
comments_article = models.ForeignKey(Article)
from django.forms import ModelForm
from article.models import Comments
class CommentForm(ModelForm):
class Meta:
model = Comments
fields = '__all__'
exclude = ['comments_article']
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
Do not consider yourself smarter than developers - this function is needed if you inherited a database
class Meta:
db_table = 'comments'
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})
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question