如何在django中进行自定义登录

时间:2016-04-12 10:08:41

标签: django python-2.7 django-forms

我是python中的新手django.i创建了一个注册页面现在我想要登录。我已经编写了登录代码,但是当我想获取登录时发布的数据是NOne。 我的代码是

def login_success(request):

    username=request.POST.get('email')
    password=request.POST.get('password')
    print "inside loginview"
    user =authenticate(username=username, password=password)
    print "username is",username
    if user is not None:
        if user.is_active:
            login(request, user)


            # return render(request,'loginsuccess.html',{})
            return HttpResponseRedirect('/success/')

        else:
            state="your account is not active"

    else:
        state="username or password is incorrect"
    print "username",username

    return render(request,'login.html',{})

我在用户名和密码中获得了NOne值

my models.py

class UserProfile(models.Model):

    first_name=models.CharField(max_length=50,blank=True ,null=True)
    last_name=models.CharField(max_length=50,blank=True ,null=True)
    password=models.CharField(max_length=50)
    email=models.EmailField()

    def __unicode__(self):
        return self.first_name or u''

我的登录模板

<!DOCTYPE html>
<html>
    <head>
        <!-- Is anyone getting tired of repeatedly entering the header over and over?? -->
        <title>Rango</title>
    </head>

    <body>
        <h1>Login to Rango</h1>

        <form id="login_form" method="post" action="/loginsuccess/">
            {% csrf_token %}
            Username: <input type="text" name="username" value="" size="50" />
            <br />
            Password: <input type="password" name="password" value="" size="50" />
            <br />

            <input type="submit" value="submit" />
        </form>

    </body>
</html>

1 个答案:

答案 0 :(得分:0)

更新1:

首先,您创建的UserProfile不是正确的方法...默认情况下,django具有User模态

因此,请从models.py中删除UserProfile类,但如果您想添加其他字段,请使用ForeignKey进行扩展,如

class UserProfile(models.Model):
    user = models.ForeignKey(User)
    phone_number = models.IntegerField()

<强>答案

您的表单方法为post,因此请在此类视图中获取帖子值

def login_success(request):
    if request.method == 'POST':
        # do your code here
        username = request.POST.get('username')
        password = request.POST.get('password')

像这样编写你的HTML

   <form id="login_form" method="post" action="">
        {% csrf_token %}
        Username: <input type="text" name="username" size="50" />
        <br />
        Password: <input type="password" name="password" size="50" />
        <br />

        <input type="submit" value="submit" />
    </form>