制作用户帐户并登录django

时间:2018-04-13 04:42:17

标签: python django

我是django的新手。我想开发一个注册页面,我想在其中添加姓名,电子邮件和密码字段。如果电子邮件已经存在它应该返回错误消息。为此我开发了以下代码。但它显示错误  * /中的SyntaxError 语法无效(views.py,第19行)以及其他一些

这是我的代码

forms.py *

from django import forms

from django.conf import settings

from django.contrib.auth.models import User

User=get_user_model

class UserLoginForm(forms.Form):

    email=forms.EmailField(label='Email',max_length=254)

    password = forms.CharField(label='Password',
                          widget=forms.PasswordInput())

    def clean(self,*args,**kwargs):
        email=self.self.cleaned_data.get("email")
        password=self.cleaned_data.get("password")
        if email and password:
            user=authenticate(email=email,password=password)
            if not user:
                raise forms.ValidationError("This email id is not registered")
            if not user.check_password(password):
                raise forms.ValidationError("Incorrect password")
            return super(UserLoginForm,self).clean(*args,**kwargs)
class RegistrationForm(forms.ModelForm):

    error_messages = {
        'duplicate_emailid': "This email id is already exists.",
        'duplicate_mobile':  "This mobile no is already exists.",
        'password_mismatch': "The two password fields didn't match.",
        'too_short': "Passwords must be at least 6 characters long.",
    }

    username= forms.CharField(label='Username', max_length=30)
    email = forms.EmailField(label='Email address',max_length=254)
    mobile =forms.CharField(label='Mobile No',max_length=10)
    password = forms.CharField(label='Password',
                          widget=forms.PasswordInput())
    confirm_password = forms.CharField(label='Confirm Password',
                        widget=forms.PasswordInput())
    class Meta:
        model = User
        fields = ['username', 'email', 'mobile', 'password','confirm_password']
    def username(self):
        username=self.cleaned_data.get("username")
        if username is None:
            msg="Plese Enter the User name"
            raise forms.ValidationError(msg)
        return username

    def clean_password(self):
        password = self.cleaned_data.get("password")
        if len(password) < 6:
            raise forms.ValidationError(
                self.error_messages['too_short'],
            )
        return password
    def clean_confirm_password(self):
        password1 = self.cleaned_data.get('password')
        confirm_password = self.cleaned_data.get('confirm_password')
        if password and confirm_password and password != confirm_password:
            raise forms.ValidationError(
                self.error_messages['password_mismatch']
            )
        return confirm_password
    def clean_email(self):
        email = self.cleaned_data.get('email')
        check_duplicate_email = User.objects.filter (email=email).exists()
        if check_duplicate_email:
            raise forms.ValidationError(
            self.error_messages['duplicate_emailid']
            )
        return email
    def clean_mobile(self):
        mobile=self.cleaned_data.get('mobile')
        check_duplicate_mobile=User.objects.filter(mobile=mobile).exists()
        if check_duplicate_mobile:
            raise forms.ValidationError(
            self.error_messages['duplicate_mobile']
            )
        return mobile

views.py

from django.shortcuts import render,redirect

from django.conf import settings

from django.contrib.auth import authenticate,get_user_model, login, logout

from django.contrib.auth.decorators import login_required

from django.contrib.auth.forms import AuthenticationForm

from django.contrib.auth.models import User

from . forms import UserLoginForm

from . forms import RegistrationForm

def login_view(request):

    title="Login"

    form=UserLoginForm(request.POST or None)

    if form.is_valid():
        email=form.cleaned_data.get("email")
        password = form.cleaned_data.get("password")
        user=authenticate(email=email,password=password)
        login(request,user)
    return render(request,"registration/signup.html",{"form":form,"title"=title})

def register_view(request):

    title="Signup"

    form = RegistrationForm(request.POST or None)

    if form.is_valid():
        user=form.save(commit=False)
        email = form.cleaned_data.get("email")
        password = form.cleaned_data.get("password")
        user=set_password(password)
        user.save()
        new_user = authenticate(email=user.email, password=password)
        login(request, new_user)
        return redirect("registration/register.html")
    return render(request, "registration/signup.html", {"form": form,"title"=title})

urls.py

from django.conf import settings

from django.conf.urls import patterns, include, url

from django.contrib.auth.models import User

from django.contrib.auth.forms import UserCreationForm

from django.views.generic import CreateView

from . import views

urlpatterns = patterns[
url(r'^login/',views.login_view,name='login'),

url(r'^signup/',views.register_view,name='register'),
                     ]

HTML

 <!DOCTYPE html>

{% load crispy_forms_tags %}

{% block content %}

<div class=='col-sm-6 col-sm-offset-3'>
<h1> {{title}} </h1>

<form method='POST' action='' enctype='multipart/form-data'>{% csrf token %}
{{ form|crispy }}
<input type='submit' class='btn btn-default' value="{{ title }}" />
</form></div>

{% endblock content %}

1 个答案:

答案 0 :(得分:0)

您可能在此行中遇到问题

return render(request,"registration/signup.html",{"form":form,"title"=title})
                               # here, should be {"form":form,"title":title}

你有两次这个问题。

请尝试下次更好地格式化代码。