简体   繁体   English

Django Model 用户登录时

[英]Django Model While User Login

Iam new in programming.我是编程新手。 I need to make a model/table in django where details of a User has to save.我需要在 django 中制作一个模型/表格,其中必须保存用户的详细信息。 If the User login It will goes to registration page if he is not completed the registration, else if he already completed the registration it will goes to home page.如果用户登录,如果他没有完成注册,它将进入注册页面,否则如果他已经完成注册,它将进入主页。

What should I do?我应该怎么办?

models.py模型.py

class UserReg(models.Model):
Name=models.CharField(max_length=200)
Date_of_Birth=models.DateField()
Age=models.IntegerField()
Gender=models.CharField(max_length=200, choices=GenderChoice)
Phone_no=models.IntegerField()
Mail=models.EmailField(unique=True)
Address=models.TextField(max_length=700)
District=models.ForeignKey(District,on_delete=models.CASCADE)
Branch=models.ForeignKey(Branch,on_delete=models.CASCADE)
Account_Type=models.CharField(max_length=200,choices=AccType)
Materials=models.ManyToManyField(Materials)

views.py视图.py

def reg(request):
form = Userform()
if request.method == 'POST':
    form=Userform(request.POST)
    if form.is_valid():
        Name=request.POST.get('Name')
        Date_of_Birth = request.POST.get('Date_of_Birth')
        Age = request.POST.get('Age')
        Gender = request.POST.get('Gender')
        Phone_no  = request.POST.get('Phone_no')
        Mail   = request.POST.get('Mail')
        Address  = request.POST.get('Address')
        District   = request.POST.get('District')
        Branch   = request.POST.get('Branch')
        Account_Type = request.POST.get('Account_Type')
        Materials = request.POST.get('Materials')
        obj=UserReg(Name=Name,Date_of_Birth=Date_of_Birth,Age=Age,Gender=Gender,Phone_no=Phone_no,Mail=Mail,Address=Address,District=District,Branch=Branch,Account_Type=Account_Type,Materials=Materials)
        obj.save()
        return redirect('/')



return render(request,'registration.html',{'form':form,})

def loginuser(request):
if request.method =='POST':
    username= request.POST['username']
    password= request.POST['password']
    user=auth.authenticate(username=username,password=password)
    if user is not None:
        auth.login(request,user)
        return redirect('/')

    else:
        messages.info(request,"invalid username or password")
        return redirect('login')

return render(request,'login.html')

First you need to bind UserReg to User model by adding OneToOne relation field to your UserReg model:首先,您需要通过将 OneToOne 关系字段添加到 UserReg model 来将 UserReg 绑定到用户 model:

class UserReg(models.Model):
   user = models.OneToOneField(User, on_delete=models.CASCADE)
   # rest of your fields

You can create modelForm for it:你可以为它创建modelForm:

    class UserRegForm(forms.ModelForm):
       class Meta:
          model = UserReg
          fields = '__all__'
          widgets = {'user': forms.HiddenInput }

In reg view first check if user have UserReg object and if not go with the view:在注册视图中,首先检查用户是否有 UserReg object,如果没有 go,请查看:

def reg(request):
  if request.user.userreg:
    return redirect ('/')

  if request.method == 'POST':
     form = UserRegForm(request.POST)
     if form.is_valid():
        form.save()
        return redirect ('/')
  else:
     form = UserRegForm(initial={'user': request.user})
  
  return render(request,'registration.html',{'form':form,})

I think best approach is to make a costume decorator我认为最好的方法是制作服装装饰师

#in your UserReg add a new field User
 class UserReg(models.Model):
     user = models.OneToOneField(User, related_name="profile", on_delete=models.CASCADE)
     ...otherfields

don't forget to import User and instantiate The user Above ur UserReg Model不要忘记导入用户并实例化用户上面的用户 UserReg Model

 from django.contrib.auth import get_user_model
  User = get_user_model()

now make your migrations run these in the command line care when you do this command you will have an error if there is already rows in your database in table UserReg to avoid please delete all the database and run the commands again if they ran without error you are good to go现在让您的迁移在命令行中运行这些,当您执行此命令时,如果您的数据库中已经存在表 UserReg 中的行以避免出现错误,请删除所有数据库并再次运行命令,如果它们运行没有错误您对 go 都很好

python manage.py makemigrations
python manage.py migrate # 

now create a new file in the same directory call it decorator.py and put this code inside which we will use to prevent user from viewing any page u want without filling his data现在在同一目录中创建一个名为 decorator.py 的新文件并将此代码放入其中,我们将使用该代码来防止用户在不填写数据的情况下查看您想要的任何页面

def complete_registration(view_func):
    def wrapper_func(request, *args, **kwargs):
       if request.user.userreg.exists(): # here we check if has a userreg profile if he has we could extra check if he had filled all fields if he passed return him to view
        return view_func(request, *args, **kwargs)
        
       else:
        return redirect('registration') # else he didnt pass if checks redirect him to profil registration page

    return wrapper_func

now we made our decorator lets use it on all views we want to restrict user to visit without filling his profile现在我们制作了我们的装饰器,可以在我们想要限制用户访问的所有视图上使用它而不填写他的个人资料

# lets import our newly decorator
from .decorators import complete_registration

lets assign the decorator to every view i want to restrict user from visiting without filling profile让我们将装饰器分配给我想限制用户在不填写配置文件的情况下访问的每个视图

 @complete_registration
 def viewname(request):
   return

 @complete_registration
  def anotherview(request):
     return

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM