Extending the User model with custom fields in Django

后端 未结 13 1444
别那么骄傲
别那么骄傲 2020-11-21 23:28

What\'s the best way to extend the User model (bundled with Django\'s authentication app) with custom fields? I would also possibly like to use the email as the username (fo

13条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 00:19

    You can Simply extend user profile by creating a new entry each time when a user is created by using Django post save signals

    models.py

    from django.db.models.signals import *
    from __future__ import unicode_literals
    
    class UserProfile(models.Model):
    
        user_name = models.OneToOneField(User, related_name='profile')
        city = models.CharField(max_length=100, null=True)
    
        def __unicode__(self):  # __str__
            return unicode(self.user_name)
    
    def create_user_profile(sender, instance, created, **kwargs):
        if created:
            userProfile.objects.create(user_name=instance)
    
    post_save.connect(create_user_profile, sender=User)
    

    This will automatically create an employee instance when a new user is created.

    If you wish to extend user model and want to add further information while creating a user you can use django-betterforms (http://django-betterforms.readthedocs.io/en/latest/multiform.html). This will create a user add form with all fields defined in the UserProfile model.

    models.py

    from django.db.models.signals import *
    from __future__ import unicode_literals
    
    class UserProfile(models.Model):
    
        user_name = models.OneToOneField(User)
        city = models.CharField(max_length=100)
    
        def __unicode__(self):  # __str__
            return unicode(self.user_name)
    

    forms.py

    from django import forms
    from django.forms import ModelForm
    from betterforms.multiform import MultiModelForm
    from django.contrib.auth.forms import UserCreationForm
    from .models import *
    
    class ProfileForm(ModelForm):
    
        class Meta:
            model = Employee
            exclude = ('user_name',)
    
    
    class addUserMultiForm(MultiModelForm):
        form_classes = {
            'user':UserCreationForm,
            'profile':ProfileForm,
        }
    

    views.py

    from django.shortcuts import redirect
    from .models import *
    from .forms import *
    from django.views.generic import CreateView
    
    class AddUser(CreateView):
        form_class = AddUserMultiForm
        template_name = "add-user.html"
        success_url = '/your-url-after-user-created'
    
        def form_valid(self, form):
            user = form['user'].save()
            profile = form['profile'].save(commit=False)
            profile.user_name = User.objects.get(username= user.username)
            profile.save()
            return redirect(self.success_url)
    

    addUser.html

    
    
        
            
            Title
        
        
            
    {% csrf_token %} {{ form }}

    urls.py

    from django.conf.urls import url, include
    from appName.views import *
    urlpatterns = [
        url(r'^add-user/$', AddUser.as_view(), name='add-user'),
    ]
    

提交回复
热议问题