2016-01-19 64 views
0

我有一个我正在开发的django项目,它允许用户创建一个帐户,登录,然后在应用程序上完成任务。我的代码中有基本的django教程,所以我可以通过管理网站添加用户,然后他们可以登录并执行操作。但是,我真正想要做的是在登录页面上创建一个部分,其中没有帐户的用户可以输入他们的名称,用户名和密码,然后使用这些凭据登录。我很漂亮新的Django,所以我没有太多的想法做什么。以下是我的models.py,views.py和login.html文件,它们可以让你知道我要开始的地方。Django:允许用户在网络应用程序上创建一个帐户

登录访问量:适用

@login_required() 
def my_view(request): 
    username = request.POST['username'] 
    password = request.POST['password'] 
    user = authenticate(username=username, password=password) 
    if user is not None: 
     if user.is_active: 
      login(request, user) 
      template_name = 'polls/index.html' 
      context_object_name = 'latest_question_list' 
      return render(request, 'polls/index.html', { 
       'latest_question_list': Question.objects.order_by("pub_date"), 
      }) 
     else: 
      return render(request, 'polls/login.html', { 
      'error_message': "Your username isn't active", 
      }) 
    else: 
     return render(request, 'polls/login.html', { 
     'error_message': "Your username doesn't exist", 
     }) 
class LoginView(generic.ListView): 
    model = Question 
    template_name = "polls/login.html" 

型号:

class Student(models.Model) 
    school_name = models.CharField(max_length=500) 
    user = models.OneToOneField(User) 
    score = models.IntegerField() 
    group = models.Charfield(max_length=200) 

登录HTML:

{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} 
<form action="{% url 'polls:logged' %}" method="post">{% csrf_token %} 

<h1>Username:</h1> 
<input type="text" name="username" id="username"/> 
<h1>Password:</h1> 
<input type="text" name="password" id="password"/> 
<input type="submit" value="Login" /> 

让我知道如果你想看到更多的代码。感谢您的帮助!

回答

0

要建立在Django用户注册表单一个简单的方法是将有:

一个观点:

def user_register(request): 
# parse your form here 
# create the user here 
# don't forget set the user.active = True and login the user 

HTML表单:

<form> 
<!-- Your HTML form should have the Username/Email/Password fields --> 
<!-- The HTML should also have the Name field as if you access it later using user.first_name it would through an exception --> 
</form> 

如果你不添加任何新的属性给用户,你可以使用内置的用户模型。但是,如果你试图扩大它 - 你可以添加一个外键映射到一个新的模式,也许像:

class UserWithMoreFields(models.Model) 
user = models.OneToOneField(User) 
# Your fields as you already have in your model. 

这就是它真的。 尽管在您的视图中有一个快速观察:

@login_required 
# Your View should not have login_required , as this view calls for a user of your website to register for it . 
+0

谢谢,这样做更有意义。我会尽力实现这个! – TyCharm

0

查阅关于built-in forms的文档部分。 UserCreationForm和SetPasswordForm应该给你一个基本的想法。您可以在视图中使用这些视图,也可以基于这些示例使用自定义逻辑构建自己的视图。

相关问题