Mark Kang Mark Kang - 1 year ago 98
Python Question

how to put a login form using django

After hours and hours of trying, i still cannot seem to make it happen.
(i refer to the link above)

basically Im trying to put a login form inside this .post_list.html using django along with the postform. (so there are 2 forms)

this is the

from django.contrib import messages
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, get_object_or_404, redirect

from .forms import PostForm, AuthenticationForm
from .models import Post

from django.contrib.auth import authenticate, login

from django.contrib.auth import login
from django.http import HttpResponseRedirect
from django.template.response import TemplateResponse

from django.contrib.auth.decorators import login_required

def post_detail(request, id=None):
#instance = Post.objects.get(id=1)
instance = get_object_or_404(Post, id=id)
context = {
"title": instance.title,
"instance": instance,
return render(request, "post_detail.html", context)

def post_list(request):

if request.method == "POST":
form = AuthenticationForm(request, data=request.POST)
if form.is_valid():
login(request, form.get_user())
return HttpResponseRedirect('/post-list/')

form = AuthenticationForm(request)

return TemplateResponse(request, 'login.html', {'form': form})
else: form = AuthenticationForm()

postform = PostForm(request.POST or None)

if postform.is_valid():
instance =
print (postform.cleaned_data.get("title"))
# message success
messages.success(request, "Successfully Created")
return HttpResponseRedirect(instance.get())
#messages.error(request, "Not Successfully Created")
queryset = Post.objects.all()#.order_by("-timestamp")
context = {
"object_list": queryset,
"title": "List",
"form": postform,
"form2": form
return render(request, "post_list.html", context)

and this is the

from django import forms

from .models import Post

class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = [

from django.contrib.auth import authenticate

class AuthenticationForm(forms.Form):
username = forms.CharField(max_length=254)
password = forms.CharField(widget=forms.PasswordInput)

def clean(self):
username = self.cleaned_data['username']
password = self.cleaned_data['password']
user = authenticate(username=username, password=password)
if user is None:
raise forms.ValidationError('invalid_login')

return self.cleaned_data

and post_lost.html

{% extends "base.html" %}
{% block content %}

<form method="post" action="">
{% csrf_token %}
Username: {{ form.username }} {{ form.username.errors }}<br>
Password: {{ form.password }} {{ form.password.errors }}<br>
{{ form.errors }}<br>
<input type="submit" value="login" />

<div class='two columns right mgr'>
<form method='POST' action=''>{% csrf_token %}
{{ form.as_p }}
<input class="button-primary" type='submit' value='Create Post' />

<div class='four columns left'>
<h1>{{ title }}</h1>

{% for obj in object_list %}

<div class="row">
<a href='{{ obj.get_absolute_url }}'>
<div class="thumbnail">
<!--<img src="..." alt="...">!-->
<div class="caption">
<h3>{{ obj.title }}<small> {{ obj.timestamp|timesince }} ago</small></h3>
<p>{{ obj.content|linebreaks|truncatechars:120 }}</p>
<!-- <p><a href='{{ obj.get_absolute_url }}' class="btn btn-primary" role="button">View</a> </p>-->

<hr />

{% endfor %}

{% endblock content %}

could you please help me out? thanks.

Answer Source

My guess is you got this issue because of naming. You passing into context the following things:

form = AuthenticationForm()
postform = PostForm(request.POST or None)
 context = {
            "object_list": queryset,
            "title": "List",
            "form": postform,
            "form2": form

So, when you try to access form.username you fail, because in the template form is a postform. And postform has no 'usarname' field.

So look like you should try this:

<form method="post" action="">
    {% csrf_token %}
    Username: {{ form2.username }} {{ form2.username.errors }}<br>
    Password: {{ form2.password }} {{ form2.password.errors }}<br>
    {{ form2.errors }}<br>
    <input type="submit" value="login" />
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download