A
A
alexse2016-03-09 23:36:09
Django
alexse, 2016-03-09 23:36:09

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)

URLs.py:
url(r'^book/(?P<alias>[^/]+)', 'books.views.add_comment'),
    url(r'^book/(?P<alias>[^/]+)', 'books.views.item'),

forms.py:
class Myform(ModelForm):
    class Meta:
        model = Comment
        fields = ('text',)

sample:
{% for comment in comments %}
            <p>{{ comment }}</p>
        {% endfor %}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
P
Pan Propan, 2016-03-10
@aleksse

tutorial.djangogirls.org/ru/django_forms/index.html
I spied on it and it worked.

D
Dmitry Voronkov, 2016-03-10
@DmitryVoronkov

{% if form %}
            <p>{{ form }}</p>
        {% endif %}

O
Oscar Django, 2016-03-10
@winordie

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'),

sample:
{% 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 question

Ask a Question

731 491 924 answers to any question