at django login my request.POST.get data are all empty, I struggle with what I missed there

1,702 views
Skip to first unread message

Sabine Maennel

unread,
Sep 26, 2014, 5:32:30 PM9/26/14
to django...@googlegroups.com
This is my login view:

def login_view(request,template_name='userauth/login.html'):

    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        print username
        print password
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                next_page = reverse('public:courselist')
            else:
                next_page = reverse('userauth:login')
                messages.error(request, "Ihr Account wurde deaktiviert. Bitte nehmen Sie Kontakt zu uns auf, wenn Sie Ihnen wieder aktivieren wollen.")
        else:
            next_page = reverse('userauth:login')
            messages.error(request, u'Ung\u00FCltiges Login')
    else:
        dictionary = {'form': form }
        return render_to_response('userauth/login.html', dictionary,  context_instance=RequestContext(request))

    return HttpResponseRedirect(next_page)


And this is my form:
from django import forms

class LoginForm(forms.Form):

    username = forms.CharField(
        max_length=100,
        widget=forms.TextInput,
        required=False,
        label="",
    )
    password = forms.CharField(
        max_length=100,
        widget=forms.TextInput,
        required=False,
        label="",
    )

I think I need to tell Django somehow about the form, but I do need really know where? Can someone please help me with figuring this out? When I print out the username and password they are both None. 

  Thanks in advance
        Sabine


Alejandro Varas G.

unread,
Sep 26, 2014, 6:08:08 PM9/26/14
to django...@googlegroups.com
Hi Sabine,

Your code looks good. Can you post you template code?

Why are you not using form `is_valid`? [0]

What version of Django are you using? You can be facing that your
request.POST is empty! [1]

This may be not what you are looking for but you can use Django
Authentication System [2]

Best

0 - https://docs.djangoproject.com/en/1.6/ref/forms/api/#using-forms-to-validate-data
1 - https://docs.djangoproject.com/en/1.6/ref/request-response/#django.http.HttpRequest.POST
2 - https://docs.djangoproject.com/en/1.4/topics/auth/#django.contrib.auth.views.login
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users...@googlegroups.com.
> To post to this group, send email to django...@googlegroups.com.
> Visit this group at http://groups.google.com/group/django-users.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/db52e99e-0ce1-469c-91f7-80fdad3272eb%40googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.



--
Alejandro Varas G.
http://alejandrovaras.me

Sabine Maennel

unread,
Sep 26, 2014, 6:30:28 PM9/26/14
to django...@googlegroups.com
Thank you Alejandro, it must be the template somehow: I had a seperate login form: 

{% extends "base/base.html" %}
{% load crispy_forms_tags %}
{% block head_content %}
    <div id="heading" class="jumbotron">
<div class ="container">
<div class ="row">
        <h2>Anmeldung bei Netteachers</h2>
</div></div>
    </div>
{% endblock %}
{% block main_content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}
<div class ="container">
<div class ="row">
     <div class="col-md-6 col-lg-6 col-sm-6">
        <form id="login_form" method="post" action="{% url 'userauth:login' %}">
            {% form crispy %}
            {% csrf_token %}
           <button type="submit" class="btn btn-success">Anmelden</button>  
      </form>
     </div>
     <div class="col-md-6 col-lg-6 col-sm-6">
         <h2>Eine Baustelle</h2>
         Derzeit werden logins nur für Administratoren verteilt. Netteachers ist noch in der Aufbauphase.
     </div>
</div>
</div>
{% endblock %}

This did not work. Forms.py is this:
from django import forms

class LoginForm(forms.Form):

    username = forms.CharField(
        max_length=100,
        widget=forms.TextInput,
        required=False,
        label="",
    )
    password = forms.CharField(
        max_length=100,
        widget=forms.TextInput,
        required=False,
        label="",
    )


I then put the form back in the navigation bar, where it did work. I will check out your links. I am still a little confused by the formhandling overall.
    Thanks a lot für your very valuable input.
           Sabine

Collin Anderson

unread,
Sep 29, 2014, 3:54:24 PM9/29/14
to django...@googlegroups.com
Use a login view like this:
@sensitive_post_parameters('password')
def login_view(request):
    form
= LoginForm(initial={'email': request.order.email})
   
if request.POST.get('login'):
        form
= LoginForm(data=request.POST)
       
if form.is_valid():
           
if user.is_active:
                auth
.login(request, form.user)
               
return redirect('public:courselist')
           
else:

                messages
.error(request, "Ihr Account wurde deaktiviert. Bitte nehmen Sie Kontakt zu uns auf, wenn Sie Ihnen wieder aktivieren wollen.")

               
return redirect('userauth:login')
   
return render(request, 'userauth/login.html', {'form': form})


and add a clean() method to your form like this:
    def clean(self):
       
if self.cleaned_data.get('username') and self.cleaned_data.get('password'):
           
self.user = authenticate(username=self.cleaned_data['username'], password=self.cleaned_data['password'])
           
if self.user is None:
               
raise forms.ValidationError('Please enter a correct username and password.')
           
elif not self.user.is_active:  # or leave this out and handle inactive case in your view above.
               
raise forms.ValidationError('This account is inactive.')
       
return self.cleaned_data


Reply all
Reply to author
Forward
0 new messages