如何为每个用户创建个人资料

时间:2020-05-01 15:15:39

标签: django

我有一个应用程序,如果用户注册,该应用程序将自动为其创建一个个人资料页面,注册和登录部分可以正常工作,但不能创建个人资料页面,我必须在管理页面。我该如何解决这个问题?

这是我的模特。py

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

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

    def save(self):
        super().save()

        img = Image.open(self.image.path)

        if img.height > 300 or img.width > 300:
            output_size = (300, 300)
            img.thumbnail(output_size)
            img.save(self.image.path)

这是我的views.py

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, f'Your Acount Has Been Created You Are Now Be Able to Login')
        return redirect('login')
else:
    form = UserRegisterForm()
return render(request, 'users/register.html', {'form':form})


@login_required
def profile(request):
if request.method == 'POST':
    u_form = UserUpdateForm(request.POST, instance=request.user)
    p_form = ProfileUpdateForm(request.POST ,request.FILES , instance=request.user.profile)
    if u_form.is_valid() and p_form.is_valid():
        u_form.save()
        p_form.save()
        messages.success(request, f'Your Acount Has Been Updated')
        return redirect('profile')
else:
    u_form = UserUpdateForm(instance=request.user)
    p_form = ProfileUpdateForm(instance=request.user.profile)

context = {
    'u_form':u_form,
    'p_form':p_form
}
return render(request, 'users/profile.html', context)

这是我的表格。py

class UserRegisterForm(UserCreationForm):
    email = forms.EmailField()

class Meta:
    model = User
    fields = ['username', 'email', 'password1', 'password2'] 


class UserUpdateForm(forms.ModelForm):
    email = forms.EmailField()

    class Meta:
        model = User
        fields = ['username', 'email'] 


class ProfileUpdateForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ['image']

这是我的信号。py

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


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

这是我的apps.py:

class UsersConfig(AppConfig):
    name = 'users'

    def ready(self):
        import users.signals

1 个答案:

答案 0 :(得分:0)

我能看到的唯一原因是信号未正确注册,请确保在应用程序的 init .py文件中引用了配置:

# my_app.__init__.py
default_app_config = 'my_app.apps.MyAppConfig'

或者,将信号移动到models.py文件,看看在创建用户时它们是否触发。作为最后的选择,保存用户表单后,尝试在视图中创建配置文件。