Search code examples
djangodjango-templatesdjango-viewsdjango-authentication

Empty form doesn't show on the page


I am building custom user authentification logic on my site. I created MyUsermodel than created form

from django import forms                                     
from django.contrib.auth.forms import UserCreationForm,UserChangeForm
from .models import MyUser

classCustomUserCreationForm(UserCreationForm):
   class Meta:
       model = MyUser
       fields = ('email',)

Than in project level urls.py file i added the following path

 urlpatterns =[ 
 path('login/',include('authorization.urls'),]

Than in authorization/urls.py i created

from django.urls import path                                  
from .views import login_form                                                                                            
urlpatterns =
[path(' ',login_form,name='login_form'),]       

In my view file i have the following method which if request == GET should return empty form and if form is_valid() it's redirect to another page

from django.http import HttpResponseRedirect               
from django.shortcuts import render                           
from .form import UserCreationForm

def login_form(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data('email')
            password = form.cleaned_data('password')
        return HttpResponseRedirect('/thank/')
    else:
        form = UserCreationForm()
    return render(request,'registration/log.html',{'form':form})

And last piece is log.html

{% extends 'main/base.html' %}                             
<form action="{% url 'login_form' %}" method="post">              
{% csrf_token %}
 {{ form }}                                
<input type="submit" value="Submit">                         
</form>

But when i run server and open http://127.0.0.1:8000/login/ I haven't anything no exceptions and haven't empty form itself


Solution

  • You are extending the main/base.html template in your log.html file; However, you did not include any {% blcok xxx %} there.

    So it will omit the entire custom html inside the log.html.

    Basically, if you have something like:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <title>Document</title>
    </head>
    <body>
        {% block content %}
    
        {% endblock %}
    </body>
    </html>
    

    in your base.html, then you should have the following for your log.html:

    {% extends 'main/base.html' %}  
    
    {% block content %}              
        <form action="{% url 'login_form' %}" method="post">              
        {% csrf_token %}
         {{ form }}                                
        <input type="submit" value="Submit">                         
        </form>
    {% endblock %}