0

我有一个 Django 项目,我目前在其中使用了默认的用户身份验证过程,并将其扩展为允许用户配置文件。我现在想为两种不同类型的用户创建配置文件,例如用户类型 1:= WP。用户类型 2:= W。

我查看了一些建议的解决方案,但想要一些关于我的特定场景和代码的具体指导。

据我了解,尝试执行此操作有三种方法 1. 代理模型 2. 1-1 关系方法(扩展用户模型) 3. 自定义用户模型。

我想使用选项 #2 - 1-1 关系方法并避免使用其他两种方法,目的是 a) 允许用户登录 b) 允许用户指定他们是用户类型 1 (WP) 还是用户类型2 (W) c) 如果用户是用户类型 1 (WP),他们将被定向到 WP 配置文件,如果用户是用户类型 2 (W),他们将被定向到用户类型 2 (W) 配置文件。

我目前在我的 models.py 中有这个(供用户使用)

from django.db import models
from django.contrib.auth.models import User
from PIL import Image
from django import forms


class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image = models.ImageField(default='default.jpg', upload_to='profile_pics')

    def __str__(self):
        return f'{self.user.username} Profile'

    def save(self, *args, **kwargs):
        super(Profile, self).save(*args, **kwargs)
        img = Image.open(self.image.path)
        if img.height > 300 or img.width > 300:
            output_size = (300,300)
            img.thumbnail(output_size)
            img.save(self.image.path)

我是否可以通过为两个不同的所需配置文件创建两个不同的模型来解决它,如下所示?

from django.db import models
from django.contrib.auth.models import User
from PIL import Image
from django import forms


class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image = models.ImageField(default='default.jpg', upload_to='profile_pics')

    def __str__(self):
        return f'{self.user.username} Profile'

    def save(self, *args, **kwargs):
        super(Profile, self).save(*args, **kwargs)
        img = Image.open(self.image.path)
        if img.height > 300 or img.width > 300:
            output_size = (300,300)
            img.thumbnail(output_size)
            img.save(self.image.path)

class WP(User):
    WP_name=models.CharField(max_length=100)
    description=models.TextField(max_length=300)

class W(User):
    company=models.CharField(max_length=100)
    requirements=models.TextField(max_length=300)
    date_posted=models.DateTimeField(default=timezone.now)

我的views.py 看起来像这样,我调用了配置文件页面,所以我是否会创建一个调用配置文件1 或配置文件2 页面的逻辑,这取决于它是什么类型的用户?

视图.py

#USERS (register) view.py
from django.shortcuts import render,redirect
from django.contrib.auth.forms import UserCreationForm
from django.contrib import messages #this allows us flash messages for testing
from django.contrib.auth.decorators import login_required
from .forms import UserRegisterForm
from .forms import UserUpdateForm
from .forms import ProfileUpdateForm

from django.contrib.auth.decorators import login_required

# Create your views here.

#Here we create python classes and they create html forms for us
#We want a registration form...so we can use the user creation form that already exists in Django

def register(request):
    if request.method =='POST':
        #this UserRegisterForm is created in forms.py and inherits from UserCreationForm (the ready made form)
        form = UserRegisterForm(request.POST) #create a form that has the data that was in request.POST
        if form.is_valid(): #is the form valid (do you have a username like this already, passwords match?
            form.save()#this just saves the account, hashes the password and it's all done for you!
            username = form.cleaned_data.get('username')
            messages.success(request,f'Account created for {username}, you can now login.')
            return redirect('socialmedia-moreinfo')

    else:
        form =UserRegisterForm() #if the form input is invalid, render the empty form again

    #above we are creating a blank form and rendering it to the template
    return render(request, 'users/register.html',{'form':form})
#different types of messages message . debug, inf success warning and error

@login_required #this is a decorator (adds functionality to an existing function)
def profile(request):
    if request.method =='POST':
        u_form =UserUpdateForm(request.POST,instance=request.user)
        p_form =ProfileUpdateForm(request.POST, request.FILES,instance=request.user.profile)

        if u_form.is_valid() and p_form.is_valid():
            u_form.save()
            p_form.save()
            messages.success(request,f'Your account has been updated')
            return redirect('profile')

    else:   
        u_form =UserUpdateForm(instance=request.user)
        p_form =ProfileUpdateForm(instance=request.user.profile)


    context={
            'u_form': u_form,
            'p_form': p_form
        }

    return render(request,'users/profile.html',context)
        #add a login required dectorator that django provides
        #we want a user to be logged in to view this profile view
        #see the very top to import decorators

我的问题是我试图避免自定义用户模型路线(有很多教程),但出于教学目的,我想以这种方式处理它。

我的问题是: 1. 我该如何解决这个问题,(需要对模型和视图进行哪些更改)以使用 1-1 关系方法创建两个用户配置文件。

  1. 我接近这个完全错误吗?我应该退出这种方法并采用自定义用户路线吗?

  2. 最后,是否有针对初学者的推荐教程,用于创建具有多个用户的项目。我一个也找不到!youtube 上有一个,但包括 REACT,这会使过程和教程复杂化。

提前致谢。

4

0 回答 0