django UserCreationForm不保存

时间:2018-12-03 18:17:15

标签: python django

绅士,用户注册有问题,数据未保存到模型Profile中,所有内容仅保存在Users中,我认为信号的工作不正确

views.py

from django.shortcuts import render, redirect
from .forms import UserRegisterForm
from .models import Profile
from django.contrib import messages
from django.contrib.auth.decorators import login_required


def register(request):
    if request.method == 'POST':
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            messages.success(request, 'Your account has been created')
            return redirect('login')
    else:
        form = UserRegisterForm()
    return render(request, 'users/register.html', {'form':form})

models.py

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

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image = models.ImageField(upload_to = 'profile_pics')

    def __str__(self):
        return f'{self.user.username} Profile'

forms.py

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

class UserRegisterForm(UserCreationForm):
    email = forms.EmailField()
    class Meta:
        model = User
        fields = ['username', 'email', 'password1', 'password2']

signals.py

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

@receiver(post_save, sender=User)
def create_profile(instance, sender, **kwargs, created):
    if created:
        Profile.objects.create(user=instance)

@receiver(post_save, sender=User)
def save_profile(sender, instance, **kwargs):
    instance.profile.save()

1 个答案:

答案 0 :(得分:0)

我发现了一个问题,只应该添加settings.py INSTALLED_APPS而不是一行“用户”,我应该添加“ users.apps.UsersConfig”, 像这样

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'users.apps.UsersConfig',
]