Answer the question
In order to leave comments, you need to log in
How to display a form?
Question in that: "How to display the form, and to receive from there the data". In programming, not long, so such a banal question. I display the comments on the same page as the form.
views.py:
def item(request, alias):
try:
item = Book.objects.get(alias=alias)
except ObjectDoesNotExist:
raise Http404
form = Myform()
comments = Comment.objects.all()
context = {
'item' : item,
'form': form,
'comments': comments,
}
return render(request, 'item.html', context)
def add_comment(request, alias):
if request.method == 'POST':
form = Myform(request.POST)
if form.is_valid():
comment = form.save(commit=False)
form.save()
else:
form = Myform()
return HttpResponseRedirect('/books/%s' % alias)
url(r'^book/(?P<alias>[^/]+)', 'books.views.add_comment'),
url(r'^book/(?P<alias>[^/]+)', 'books.views.item'),
class Myform(ModelForm):
class Meta:
model = Comment
fields = ('text',)
{% for comment in comments %}
<p>{{ comment }}</p>
{% endfor %}
Answer the question
In order to leave comments, you need to log in
tutorial.djangogirls.org/ru/django_forms/index.html
I spied on it and it worked.
urls.py
url(r'^book/(?P<alias>[^/]+)/add_comment/$', 'books.views.add_comment',
name="book_add_comment"),
url(r'^book/(?P<alias>[^/]+)/$', 'books.views.item'),
{% for comment in comments %}
<p>{{ comment.text }}</p>
{% endfor %}
<form action="{% url "book_add_comment" alias=item.alias %}" method="post">
{% csrf_token %}
{{ form }}
</form>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question