Mark Kang Mark Kang - 4 months ago 14
Python Question

how to put a login form using django

After hours and hours of trying, i still cannot seem to make it happen.

http://imgur.com/MehXOeo
(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 views.py

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

else:
form = AuthenticationForm(request)

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


postform = PostForm(request.POST or None)

if postform.is_valid():
instance = postform.save(commit=False)
print (postform.cleaned_data.get("title"))
instance.save()
# message success
messages.success(request, "Successfully Created")
return HttpResponseRedirect(instance.get())
#else:
#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 forms.py

from django import forms

from .models import Post

class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = [
"title",
"content"
]

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" />
</form>


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

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

{% for obj in object_list %}



<div class="row">
<div>
<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>-->
</div>


</div></a>
</div>
<hr />
</div>

{% endfor %}

</div>
{% endblock content %}


could you please help me out? thanks.

Answer

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" />
</form>
Comments