添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
相关文章推荐
飞奔的绿茶  ·  How to write directly ...·  2 月前    · 
害羞的芹菜  ·  jquery 屏蔽checkbox ...·  4 月前    · 
高大的手术刀  ·  Comparison Operators ...·  5 月前    · 
冲动的西瓜  ·  Python ...·  1 年前    · 
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I'm having some trouble logging in users. I have the following views and template:

views.py

def login(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = auth.authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                auth.login(request, user)
                return HttpResponseRedirect('/')
            else:
                return HttpResponseRedirect('disabled account')
        else:
            return HttpResponseRedirect('/invalid')
    else:
        return render(request, 'login_page.html', {})

login_page.html

{% block content %}
    {% if form.errors %}
        <p class="error"> sorry, thats not a valid username or password</p>
    {% endif %}
<form action="/login/" method="post"> 
    <label for="username">User name:</label>
    <input type="text" name="username" value="" id="username">
    <label for="password">Password:</label>
    <input type="text" name="password" value="" id="password">
    <input type="submit" value="login" />
</form>
{% endblock %}

My problem is, whenever i hit submit in the login form, no matter what the values are, the page is redirected to the /invald/ url. I have a user set up using the admin function but i still keep getting this error. Does anyone know what the problem may be?

Do i need a forms.py file with anything in it?

Updated views:

def login(request):
    form = LoginForm(request.POST)
    if form.is_valid():
         username = form.cleaned_data["username"]
         password = form.cleaned_data["password"]
         user = authenticate(username=username, password=password)
         if user is not None:
            if user.is_active:
                login(request, user)
                return redirect('loggedin.html')
            else:
                return HttpResponse("Account deleted or disabled")
    return render(request, "login_page.html", {'form': form})

updated form:

from django import forms
from django.contrib.auth import authenticate, login, logout, get_user_model
class LoginForm(forms.Form):
    username = forms.CharField()
    password = forms.CharField(widget=forms.PasswordInput)
def clean(self, *args, **kwargs):
    username = self.cleaned_data.get("username")
    password = self.cleaned_data.get("password")
    if username and password:
        user = authenticate(username=username, password=password)
        if not user:
            raise forms.ValidationError("User does not exist.")
        if not user.is_active:
            raise forms.ValidationError("User is no longer active.")
    return super(UserLoginForm, self).clean(*args, **kwargs)

updated login_page.html

{% block content %}
    {% if form.errors %}
        <p class="error"> sorry, thats not a valid username or password</p>
    {% endif %}
<form action="{% url 'login' %}" method="post"> 
    {{  form  }}
    <input type="submit" value="login" />
</form>
{% endblock %}

urls:

    url(r'^admin/', admin.site.urls),
    url(r'^login/', views.login, name='login'),
    url(r'^logout/', views.logout, name='logout'),
    url(r'^invalid/', views.invalid_login, name='invalid_login'),
    url(r'^loggedin/', views.loggedin, name='loggedin'),
    url(r'^$', views.index, name='index'),
                The user entry does exist and I am entering the details in correctly, that's what has me stumped.
– Abjilla22
                Sep 1, 2016 at 6:13
                Try to use provided by django django.contrib.auth.forms.AuthenticationForm (docs.djangoproject.com/en/1.10/topics/auth/default/…). Then you could get error description.
– atn
                Sep 1, 2016 at 6:41
    reg = User()
    reg.username = request.POST['register_username']
    reg.set_password(request.POST['register_password']) #like this line
    reg.save()

not reg.password=request.POST['register_password']

I suggest you make a forms.py file and in here make a class like so:

from django import forms
from django.contrib.auth import authenticate, login, logout, get_user_model
class LoginForm(forms.Form):
    username = forms.CharField()
    password = forms.CharField(widget=forms.PasswordInput)
    def clean(self, *args, **kwargs):
        username = self.cleaned_data.get("username")
        password = self.cleaned_data.get("password")
        if username and password:
            user = authenticate(username=username, password=password)
            if not user:
                raise forms.ValidationError("User does not exist.")
            if not user.is_active:
                raise forms.ValidationError("User is no longer active.")
        return super(UserLoginForm, self).clean(*args, **kwargs)

Then in your views import Login form. Create a view as such:

def my_login_view(request):
    form = LoginForm(request.POST)
    if form.is_valid():
        username = form.cleaned_data["username"]
        password = form.cleaned_data["password"]
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                return redirect('someurl')
            else:
                return redirect('someotherurl')
    return render(request, "your_template_to_process_this_view", {'form': form})

In your html template you can call the form using the convention below. For this shortcut to the url to work you need an app_name = "yourappname" at the top of your url file.

<form method="POST" action="{% url 'yourappname:name_given_to_url_in_urls_file' %}">
  {% csrf_token %}
  {{ form }}
<input type="submit" class="btn-success" value="Login"/>
</form>
                you need to import it in your views file: from .forms import LoginForm and also make sure you have other required imports in the views file.
– BigMonkey89WithaLeg
                Sep 1, 2016 at 8:17
                Fixed that, it works now except im back to the first problem - submitting the user data in the form just returns a refreshed login page.
– Abjilla22
                Sep 1, 2016 at 9:40
                I had the same problem as you before. It is processing everything but being redirected improperly. The view function my_login_view, you need to create a url for this such as url(r'^login/$', views.my_login_view, name='login'), In the action of the form you call name given to the url which is login in this case. Then you need to create the page it needs to send the user to after login in. You replace 'someurl' with this url to go to the account, or homepage, etc. By the way if this worked, can you give it an up or an accept so other users can use it. Thank you.
– BigMonkey89WithaLeg
                Sep 1, 2016 at 15:43
                I have that, so I dont think it's the problem (url(r'^login/', views.login, name='login')
– Abjilla22
                Sep 1, 2016 at 15:52
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.