V
V
vhsporno2019-04-22 22:08:09
Django
vhsporno, 2019-04-22 22:08:09

Why doesn't the form render in Django?

I'm doing the dock dzhangi version 1.8. I do everything according to the instructions, even if I copy-paste the code, it does not work. What's my mistake?
views.py

from .forms import NameForm
def get_name(request):
  if request.method == "POST":
    form = NameForm(request.POST)
    if form.is_valid():
      return HttpResponseRedirect('/thanks/')
  elif request.method == "GET":
    form = NameForm()
  return render(request, 'index.html', {'form': form})

forms.py
from django import forms
class NameForm(forms.Form):
    your_name = forms.CharField(label='Your name', max_length=100)

index.html

{% extends "base_generic.html" %}
{% block content %}
{% if latest_twits %}
<div>
 	<ul>
 		{% for twits in latest_twits %}
 			<li><p>{{twits.text_twitt}}</p></li>
 			{{twits.user_id}}
 			<br>
 		{% endfor %}
 	</ul>

 </div>

 <br>
 <form method="post">
  {% csrf_token %}
  {{form.as_p}}

<input type="submit" value="login">
</form>
 {% endif %} 
{% endblock %}

urls.py if needed
from django.conf.urls import url, include
from . import views 
urlpatterns = [
  url(r'^$', views.IndexView.as_view(), name='index'),
    url(r'^accounts/', include('django.contrib.auth.urls')),
]

I've been breaking my head for two days, I can't make an elementary form

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Dimonchik, 2019-04-22
@dimonchik2013

I've been breaking my head for two days, I can't make an elementary form

see the picture in my profile
1) leave ONLY the form in the template index
2) grow

H
howuu, 2019-04-22
@howuu

Most likely this condition is not met . Therefore, the form is not displayed, take it out of the condition, or make it so that it is observed

E
Eugene, 2019-04-23
@immaculate

Not most likely, but definitely the condition is not met:
Because such a variable is not passed to the template at all.
And frankly, the code looks just awful. Django 1.8 is outdated a long time ago, the current LTS version is 2.2. And even for 1.8 the code is badly written. After all, there have been good tutorials on Django for a long time, what do you use when writing such code? If you switch to Class Based Views, then the code will become shorter and clearer. Yes, even with functions, form processing code has been written much easier for at least 10 years:

form = SomeForm(request.POST or None)
if form.is_valid():
    return redirect('index')
return render(form)

And it's better not to render the forms manually in the template, but to use the django-crispy-forms.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question