Django create custom UserCreationForm

Włączyłem moduł auth użytkownika w Django, jednak gdy używam UserCreationForm, pyta tylko o nazwę użytkownika i dwa pola potwierdzenia hasła/hasła. Chcę również pola email i fullname, wszystkie ustawione jako wymagane pola.

Zrobiłem to:

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

class RegisterForm(UserCreationForm):
    email = forms.EmailField(label = "Email")
    fullname = forms.CharField(label = "Full name")

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

Teraz formularz pokazuje nowe pola, ale nie zapisuje ich w bazie danych.

Jak mogę to naprawić?
Author: VLAZ, 2011-04-21

3 answers

Nie ma takiego pola o nazwie fullname w modelu użytkownika.

Jeśli chcesz zapisać nazwę używając oryginalnego modelu, musisz przechowywać ją oddzielnie jako imię i nazwisko.

Edit: jeśli chcesz mieć tylko jedno pole w formularzu i nadal używać oryginalnego modelu użytkownika, Użyj następującego wzoru:

Możesz zrobić coś takiego:

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

class RegisterForm(UserCreationForm):
    email = forms.EmailField(label = "Email")
    fullname = forms.CharField(label = "First name")

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

Teraz musisz zrobić to, co powiedział manji i nadpisać metodę save, jednak ponieważ model użytkownika nie ma pole fullname powinno wyglądać tak:

def save(self, commit=True):
        user = super(RegisterForm, self).save(commit=False)
        first_name, last_name = self.cleaned_data["fullname"].split()
        user.first_name = first_name
        user.last_name = last_name
        user.email = self.cleaned_data["email"]
        if commit:
            user.save()
        return user

Uwaga: powinieneś dodać czystą metodę dla pola fullname, która zapewni, że wprowadzona pełna nazwa zawiera tylko dwie części, imię i nazwisko oraz że ma inne ważne znaki.

Kod źródłowy odniesienia dla modelu użytkownika:

http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/models.py#L201
 25
Author: chandsie,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-04-21 15:07:26

Musisz obejść UserCreationForm.save() metodę:

    def save(self, commit=True):
        user = super(RegisterForm, self).save(commit=False)
        user.fullname = self.cleaned_data["fullname"]
        user.email = self.cleaned_data["email"]
        if commit:
            user.save()
        return user

Http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/forms.py#L10

 6
Author: manji,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-04-21 14:19:33

In django 1.10 oto co napisałem w admin.py aby dodać first_name, wyślij i last_namedo domyślnego użytkownika django formularza tworzenia

from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib import admin
from django.contrib.auth.models import Group, User

# first unregister the existing useradmin...
admin.site.unregister(User)

class UserAdmin(BaseUserAdmin):
    # The forms to add and change user instances
    # The fields to be used in displaying the User model.
    # These override the definitions on the base UserAdmin
    # that reference specific fields on auth.User.
    list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff')
    fieldsets = (
    (None, {'fields': ('username', 'password')}),
    ('Personal info', {'fields': ('first_name', 'last_name', 'email',)}),
    ('Permissions', {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}),
    ('Important dates', {'fields': ('last_login', 'date_joined')}),)
    # add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
    # overrides get_fieldsets to use this attribute when creating a user.
    add_fieldsets = (
    (None, {
        'classes': ('wide',),
        'fields': ('username', 'email', 'first_name', 'last_name', 'password1', 'password2')}),)
    list_filter = ('is_staff', 'is_superuser', 'is_active', 'groups')
    search_fields = ('username', 'first_name', 'last_name', 'email')
    ordering = ('username',)
    filter_horizontal = ('groups', 'user_permissions',)

# Now register the new UserAdmin...
admin.site.register(User, UserAdmin)
 4
Author: Lucas B,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-23 12:33:21