Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 扩展新用户创建表单Django_Python_Django_Model - Fatal编程技术网

Python 扩展新用户创建表单Django

Python 扩展新用户创建表单Django,python,django,model,Python,Django,Model,我正在尝试将位置字段添加到用户配置文件中,并将其与用户关联。我现在有这样的东西: 这是my models.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(Use

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

这是my models.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 tho。我想我错过了一些东西,比如:

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

但是我不知道该把它放在哪里。

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


您是否尝试对配置文件使用简单的内联?是的,它将显示在底部,但否则它将工作

from django.contrib import admin
from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin
from website.users.models import UserProfile

admin.site.unregister(User)

class UserProfileInline(admin.StackedInline):
    model = UserProfile
    max_num = 1

class UserProfileAdmin(UserAdmin):
    inlines = [UserProfileInline]
    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',)}),
    )

admin.site.register(User, UserProfileAdmin)

我将非常感谢对我的代码的实际帮助。我读过很多不同的页面,每个页面上的人都做着不同的事情。阅读更多内容并不能帮助我更好地理解代码。此外,在django.contrib.auth的情况下,模型继承并不好,用户模型的扩展应该存在于UserProfile模型中。您的代码似乎有错误的缩进。如果您更正缩进,我们将更容易调试您的代码。我注意到的一件事是,如果您希望电子邮件是必需的,只需将required=True参数传递给它,而不是手动验证它。我确实尝试过这样做,但我得到了这个错误,我不知道它是什么意思,也不知道它在哪里出错
列user_id不唯一
这是因为您没有将UserProfile类中的“user”字段声明为-to-one*编辑:哦,天哪,您已将其声明为OneToOneField…您是否正在尝试插入多个地址?用户最多只能有一个配置文件,因此将“max_num”选项添加到已编辑的内联中。很抱歉延迟回复:)我已完成该项目,但感谢您的帮助!对于内置的django函数,我真的有一段糟糕的经历,希望我不必再使用它了!:)