本文介绍了使用django框架创建的Modifying Sign Up选项卡的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我制作了一个注册选项卡,用于注册新用户并登录页面,该页面使注册用户可以继续使用该网站.我想如果任何注册用户(具有注册电子邮件)尝试再次注册,应该弹出一条错误消息,提示您已经有一个帐户.请登录'.我将注册用户的数据存储在models.py中创建的名为SignedUpUsers的表中.请帮助我完成任务.

I have made a sign up tab that registers new users and log in page that allows the registered users to continue with the site. I want if any registered user (having a registered email) tries to sign up again , an error message should pop up saying 'You are already having an account. Please Log in'.I stored the data(s) of registered user(s) in a table created in models.py named SignedUpUsers.Please help me achieve my task.

models.py


# Create your models here.


class SignedUpUsers(models.Model):
    email = models.EmailField(max_length=122)
    name = models.CharField(max_length=122)
    username = models.CharField(max_length=122)
    password = models.CharField(max_length=122)
    date = models.DateField()

    def __str__(self):
        return self.name

views.py

from Home.models import SignedUpUsers
from django.contrib import messages
from datetime import datetime

def login(request):
    return render(request, 'login.html')


def signup(request):
    if request.method == 'POST':
        name = request.POST.get('name')
        email = request.POST.get('email')
        username = request.POST.get('username')
        password = request.POST.get('password')
        cont = SignedUpUsers(name=name,email=email,username=username,password=password,date=datetime.today())
        cont.save()
        messages.success(request,"\t\tYour account has successfully been created . Kindly Log In\t\t")
    return render(request, 'signup.html')

signup.html

<!--Form-->
<form method="post" action="/signup" style="
    position: absolute;
    top: 260px;
    left: 500px;
    font-size: larger;
">
    {%csrf_token%}
    <!--Email-->
  <div class="form-group" >
    <label for="email">Email address</label>
    <input type="email" size="25" class="form-control" id="email" name="email" placeholder="[email protected]" style="block-size: 25px; position: absolute; left: 120px;">
  </div>
    <!--Name-->
    <div class="form-group" >
    <label for="name" style="position: absolute;left: 0px;top: 30px;">Name</label>
    <input type="text" size="25" class="form-control" id="name" name="name" placeholder="Arbaaz Ahmed" style="block-size: 25px;position: absolute;left: 120px;top: 30px;">
  </div>
    <!--Username-->
    <div class="form-group" >
    <label for="username" style="position: absolute;left: 0px;top: 60px;">Username</label>
    <input type="text" size="25" class="form-control" id="username" name="username" placeholder="arbaazahmed2134" style="block-size: 25px;position: absolute;left: 120px;top: 60px;">
  </div>
    <!--Password-->
    <div class="form-group" >
    <label for="password" style="position: absolute;left: 0px;top: 90px;">Password</label>
    <input type="password" class="form-control" size="25" id="password" name="password" style="block-size: 25px;position: absolute;left: 120px;top: 90px;">
  </div>
    <!--Sign up Button-->
    <button type="submit" class="btn btn-primary" style="
    position: absolute;
    top: 130px;
    left: 120px;
    background-color: antiquewhite;
    height: 27px;
    width: 100px
">Sign Up</button>
</form>

<!--Account Created-->
{% if messages %}
{% for message in messages%}
<div class="alert alert-{{message.tags}}" role="alert" style="position: absolute; background-color: aqua; left: 470px; top: 430px">
  <!--<h4 class="alert-heading">Well done!</h4>-->
    {{ message }}
</div>
{% endfor %}
{% endif %}

推荐答案

好的,所以这里是完整的解决方案.我已经对您现有的解决方案进行了一些修改,希望对您有所帮助.

Ok, so here is full solution. I have done some modifications to your existing solution, I hope this will help you.

Django内置了 User 模型已经内置了身份验证逻辑.很棒的是,它也可以扩展.因此,我创建了 UserDetails 模型,该模型使用 OneToOneField 扩展了 User .创建以下代码并将其放置在models.py中.

Django comes with built in User model which already have authentication logic built in. Great thing is, it can be extended too. So I created UserDetails model which extends User using OneToOneField. Create and put following code in models.py .

models.py

from django.db import models
from django.contrib.auth.models import User

class UserDetails(models.Model):
    user = models.OneToOneField(User,on_delete=models.CASCADE)
    name = models.CharField(max_length=122)
    dob = models.DateField()

    def __str__(self):
        return self.name

创建完迁移后,请使用以下命令 python manage.py makemigrations 创建迁移,然后再执行 python manage.py migration

After creating that, create migrations using following command python manage.py makemigrations and after that python manage.py migrate

处理注册逻辑:

我们已经创建了模型,现在可以从用户那里获取数据.我们需要表格.Django内置了对处理表单逻辑的支持.我创建了两个模型表单作为 UserForm UserDetailsForm .这是一个棘手的部分,两种形式都充当单独的形式,每种形式都不知道其他形式.因此,我创建了一个表单集,稍后将使用它在视图内将 User UserDetails 链接起来.创建以下代码并将其放入Forms.py中.

We already have created our models, now to get data from user We need forms. Django have built in support for handling forms logic. I created two model forms as UserForm and UserDetailsForm. Here comes a tricky part, both forms are acting as a individual forms and each form is not aware of other. So I created a formset which is going to be used later to link our User with UserDetails inside view. Create and put following code in forms.py.

forms.py

from django import forms
from .models import UserDetails
from django.contrib.auth.models import User 
from django.contrib.auth.forms import UserCreationForm

class UserForm(UserCreationForm):
   class Meta:
      model = User
      fields = ('email','username','password1', 'password2',)

class UserDetailsForm(forms.ModelForm):
    class Meta:
        model = UserDetails
        fields = ('name', 'dob',)


from django.forms import inlineformset_factory
# Formset is combining UserForm and UserDetailsForm
UserDetailsFormSet = inlineformset_factory(User, UserDetails, form=UserDetailsForm, 
extra=1, can_delete = False)

要呈现两种形式,请创建一个模板 signUpTemplate.html .(注意:您可以稍后对其进行样式设置)

To render both forms create a template signUpTemplate.html. (Note: You can style it later)

signUpTemplate.html

<form method="POST">
    {% csrf_token %}
    {{ user_form.as_p }}
    {{ user_details_form.as_p }}
    <button type="submit">Submit</button>
</form>

现在,我已将视图创建为 signUpView ,该视图将处理SignUp请求.在这里,我在上下文中传递了 UserForm UserDetailsFormSet 并使用模板呈现了表单.如果您在 signUpTemplate 中仔细看过,我正在使用单个表单标签< form> *** code ***</form> 来呈现两个表单将强制在单个请求中同时发送这两个表格.

Now, I have created view as signUpView which will handle SignUp requests. Here I passed UserForm and UserDetailsFormSet in context and rendered the form using template. If you have seen carefully in signUpTemplate I am using single form tag <form>***code***</form> to render both the forms as it will force to send both the forms in single request.

现在这是我在视图中处理表单数据的方式.首先,我检查 UserForm .如果UserForm有效,那么我将处理 UserDetailsFormSet 并在其中传递 UserForm 的实例(您可能在save方法中看到了 commit = false 参数.参数表示仅将其保存在内存中而不是实际数据库中).如果 UserDetailsFormSet 是有效的,那么我在两种形式上都调用save()方法.如果表单无效,它将自动在模板*(这是内置表单的功能)*上呈现错误.这是views.py中的视图代码.

Now this is how I am processing the forms data in view. First I check for UserForm. If UserForm is valid then I process UserDetailsFormSet and pass instance of UserForm in it (you may have seen commit=false parameter in save method. this parameter means that just save it in memory not in actual database). If UserDetailsFormSet is valid then I am calling the save() method on both forms. If forms are not valid then it will automatically render the error on template*(this is the power of built in forms)*. Here is the view code in views.py .

views.py

from django.shortcuts import render,redirect
from django.conf import settings
from .forms import UserForm, UserDetailsFormSet

def signUpView(request):
    user_form = UserForm(request.POST or None)
    user_details_form = UserDetailsFormSet(request.POST or None)

    if request.method == 'POST':
        user_form = UserForm(request.POST)

        if user_form.is_valid():
            user = user_form.save(commit=False)
            user_details_form = UserDetailsFormSet(request.POST,instance=user)

            if user_details_form.is_valid():
                user.save()
                user_details_form.save()
                return redirect('login')

    context = {
        'user_form': user_form,
        'user_details_form': user_details_form,
    }

    return render(request, 'signUpTemplate.html',context=context)

处理登录逻辑:

登录功能非常简单.为了处理登录,我创建了 loginView .Django提供了内置的 AuthenticationForm 来处理 User 身份验证.要呈现 AuthenticationForm ,请创建模板 loginTemplate.html .

Login functionality is pretty straight forward. To handle login I have created loginView. Django provides built in AuthenticationForm for handling User authentication. To render AuthenticationForm create a template loginTemplate.html.

loginTemplate.html

<form method="POST">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Submit</button>
</form>

login()方法是Django的内置功能,用于处理用户登录.将以下代码放在views.py中(注意:在 redirect()方法中成功登录后,请不要忘记添加URL).

The login() method is Django's built in functionality to handle User Login. Put following code in views.py (Note: do not forget to add URL after successful login in redirect() method).

views.py

from django.contrib.auth import login
from django.contrib.auth.forms import AuthenticationForm
from django.conf import settings

def loginView(request):
    form = AuthenticationForm(request.POST or None)

    if request.method == 'POST':
        form = AuthenticationForm(data=request.POST)
        if form.is_valid():
            user = form.get_user()
            login(request, user)
            return redirect('URL_after_successful_login')

    return render(request, 'loginTemplate.html', context = {'form': form})

我们已经完成了所有主要部分,现在我们可以在应用程序的urls.py文件中注册这两个视图.

As we have done all the main part, now we can register both views in our apps urls.py file.

urls.py

from .views import index,loginView,signUpView
from django.urls import path

urlpatterns = [
    path('', index, name='index'),
    path('login', loginView, name = 'login' ),
    path('signup', signUpView, name = 'signup')
]

在您的项目urls文件中也不要忘记通过将 path('',include('your_app.urls'))放在urlpatterns中来添加对应用程序url文件的引用(注意:替换your_app和您的应用名称)

also in your projects urls file do not forget to add referance to your apps url file by putting path('', include('your_app.urls')) in urlpatterns (Note: replace your_app with your appname)

现在,您可以使用 python manage.py runserver 命令运行服务器.转到您的Web浏览器,浏览 localhost:port/signup 以获得注册页面,并浏览 localhost:port/login 以获得登录页面.

Now you can run the server by using python manage.py runserver command. Go to your web browser and browse localhost:port/signup to get signup page, and localhost:port/login to get login page.

我希望您熟悉管理网站(即创建超级用户并登录到管理站点),请按照以下步骤在管理网站上注册您的模型.并使用您的超级用户凭据登录,并在管理站点上检查 User UserDetails 表.

I hope you are familiar with admin site (i.e creation of super user and login into admin site), register your model with admin site as follows. And login with your super user credentials and check User and UserDetails tables at admin site.

admin.py

from django.contrib import admin
from .models import UserDetails

admin.site.register(UserDetails)

我希望这会对您有所帮助.:)

I hope this will help you. :)

这篇关于使用django框架创建的Modifying Sign Up选项卡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 15:35