Django extra user registration details not saving to database

馋奶兔 提交于 2021-02-10 09:43:55

问题


I have been trying to extend the django user profile but it won't save the extra details to the database which is a user_type of business, student, tourist and I can't figure out why. Any help would be appreciated.

It doesn't save in the DB as null, it is saving as just blank.

Using python 3 with the latest version of django.

Forms.py:

from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.forms import ModelChoiceField
from django.contrib.auth.models import User, Group
from .models import UserProfile


class RegisterForm(UserCreationForm):

    first_name = forms.CharField(max_length=50, required=False, 
help_text='Not required.')
    last_name = forms.CharField(max_length=50, required=False, 
help_text='Not required.')
    email = forms.EmailField(max_length=300, required=True, 
help_text='Please input a valid email address.')

    user_types = ((1, 'Business'), (2, 'Student'), (3, 'Tourist'))

    user_type = forms.ChoiceField(choices = user_types)

    class Meta:
        model = User
       fields = ('username', 'first_name', 'last_name', 'email', 'user_type', 'password1', 'password2',)

models.py

from django.db import models
from django.contrib.auth.models import User
from django.dispatch import receiver
from django.db.models.signals import post_save
from django import forms


ADMIN = 0
BUSINESS = 1
STUDENT = 2
TOURIST = 3

class UserProfile(models.Model):

    user_choices = ( (0, 'Admin'),
            (1, 'Business'),
            (2, 'Student'),
            (3, 'Tourist'),
            )
    # Link UserProfile to User model
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    # Add attributes to the user model
    user_type = models.CharField(max_length = 50,
                                 choices = user_choices,
                               #  default = 'Business',
                                 blank = False)

    def __str__(self):
        return self.user.username

@receiver(post_save, sender = User)
def create_user_profile( sender, instance, created, **kwargs):
    if created:
        UserProfile.objects.create(user = instance)
    instance.userprofile.save()

Views.py

def register(request):

    if request.method == 'POST':
        form = RegisterForm(data=request.POST)
        if form.is_valid():
            profile = form.save(commit=False)
            profile.user = request.user
            profile.save()

          #  form.save()
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password1')
            user_group = form.cleaned_data.get('user_type')
            user = authenticate(username = username, password = password)
            login(request, user)

            if user_group == 'Business':
                return render(request, 'users/business.html')
            elif user_group == 'Student':
                return render(request, 'users/student.html')
            elif user_group == 'Tourist':
                 return render(request, 'users/tourist.html')
            else:
                return redirect('main:index')
        else:
            print(RegisterForm.errors)

    else:
        form = RegisterForm()
    return render(request, 'users/register.html', {'form': form})
#    return HttpResponseRedirect(reverse('main:index'))


def business_view(request):
    return render(request, 'users/business.html')

def student_view(request):
    return render(request, 'users/student.html')

def tourist_view(request):
    return render(request, 'users/tourist.html')

回答1:


Your form meta model is User, so when you try:

profile = form.save(commit=False)

the variable profile is an instance of the User class, so, since you have the signal that creates the UserProfile instance, you should use this code:

        user = form.save()
        profile = user.userprofile
        user_group = form.cleaned_data.get('user_type')
        profile.user_type = user_group
        profile.save()

instead of:

        profile = form.save(commit=False)
        profile.user = request.user
        profile.save()


来源:https://stackoverflow.com/questions/46876774/django-extra-user-registration-details-not-saving-to-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!