gpt4 book ai didi

python - 扩展新用户创建表单,Django

转载 作者:太空宇宙 更新时间:2023-11-03 14:33:10 25 4
gpt4 key购买 nike

我正在尝试将位置字段添加到用户配置文件并将其与用户相关联。我目前有这样的东西:

这是我的模型.py:

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

class UserProfile(models.Model):
user = models.OneToOneField(User)
location = models.CharField(('location'),max_length=30, blank=False)

def create_user_profile(sender, instance, created, **kwargs):
if created:
profile = UserProfile.objects.create(user=instance)
profile.save()

post_save.connect(create_user_profile, sender=User)

这是我的 admin.py:

from django.contrib import admin
from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django import forms
from UserProfile.models import UserProfile
from django.contrib.admin.views.main import *

class MyUserCreationForm(UserCreationForm):

username = forms.RegexField(label=("Username"), max_length=30, regex=r'^[\w.@+-]+$', help_text = ("Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only."),error_messages = {'invalid': ("This value may contain only letters, numbers and @/./+/-/_ characters.")})
password1 = forms.CharField(label=("Password"), widget=forms.PasswordInput)
password2 = forms.CharField(label=("Password confirmation"), widget=forms.PasswordInput, help_text = ("Enter the same password as above, for verification."))
email = forms.EmailField(label=("Email address"))

class Meta:
model = User
fields = ("username",)

def clean_username(self):
username = self.cleaned_data["username"]
try:
User.objects.get(username=username)
except User.DoesNotExist:
return username
raise forms.ValidationError(("A user with that username already exists."))

def clean_email(self):
email = self.cleaned_data["email"]
if email == "":
raise forms.ValidationError((""))
return email

def clean_password2(self):
password1 = self.cleaned_data.get("password1", "")
password2 = self.cleaned_data["password2"]
if password1 != password2:
raise forms.ValidationError(("The two password fields didn't match."))
return password2

def save(self, commit=True):
user = super(UserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user

class MyUserChangeForm(UserChangeForm):
username = forms.RegexField(label=("Username"), max_length=30, regex=r'^[\w.@+-]+$',
help_text = ("Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only."),
error_messages = {'invalid': ("This value may contain only letters, numbers and @/./+/-/_ characters.")})
location = forms.CharField(label=("Location"),max_length=30)

class Meta:
model = User

def __init__(self, *args, **kwargs):
super(UserChangeForm, self).__init__(*args, **kwargs)
f = self.fields.get('user_permissions', None)
if f is not None:
f.queryset = f.queryset.select_related('content_type')


class CustomUserAdmin(UserAdmin):
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('username', 'email', 'password1', 'password2')}
),
)
fieldsets = (
(None, {'fields': ('username', 'password')}),
(('Personal info'), {'fields': ('first_name', 'last_name', 'email', 'location')}),
(('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser', 'user_permissions')}),
(('Important dates'), {'fields': ('last_login', 'date_joined')}),
(('Groups'), {'fields': ('groups',)}),
)
add_form = MyUserCreationForm
form = MyUserChangeForm

admin.site.unregister(User)
admin.site.register(User, CustomUserAdmin)

我不完全理解 Django/python 代码,我知道这段代码中缺少一些东西,因为当我添加一个新用户时,它不会在数据库中保存 Location 字段。它保存了用户 ID。我想我错过了类似的东西:

request.user.get_profile().location = self.cleaned_data["location"]

但我不确定把它放在哪里。

最佳答案

您可以为此使用模型继承,它会为您做类似的事情...

Model Inheritance and proxy models...

关于python - 扩展新用户创建表单,Django,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7027985/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com