在django扩展用户模型中发布配置文件信息(用户没有配置文件) [英] post profile information in django extended user model (user has no profile)

查看:58
本文介绍了在django扩展用户模型中发布配置文件信息(用户没有配置文件)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这是一个常见的话题,但是,由于Web和stackoverflow上的所有可用资源,我无法正常使用表单.

I know that this is a frequent topic, but however, with all the resources available on the web and stackoverflow, I couldn't get my form to work properly.

我收到此错误:异常类型:RelatedObjectDoesNotExist,异常值:用户没有个人资料.

这是我在Django中的设置.

Here is my setup in Django.

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

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
    location = models.CharField(max_length=30, blank=True)
    birth_date = models.DateField(null=True, blank=True)

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

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if kwargs.get('created', False):
         Profile.objects.create(user=kwargs['instance'])
post_save.connect(create_user_profile,sender=User)

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

forms.py

来自django.contrib.auth.models的

forms.py

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

class SignUpForm(UserCreationForm):
    birth_date = forms.DateField()
    location = forms.CharField()
    password1 = forms.CharField(label=("Password"), widget=forms.PasswordInput) 
    password2 = forms.CharField(label=("Confirm password"), widget=forms.PasswordInput)

    class Meta:
        model = User
        fields = ('username', 'first_name', 'last_name', 'location','email', 'birth_date')
        widgets = {
            'birth_date': forms.DateInput(attrs={'class':'datepicker'}),
        }
        labels = {
            'username': ('Capser name'),
        }
        help_texts = {
            'username' : None,
            'birth_date': None,
        }

views.py

class UserFormView(View):
    form_class = SignUpForm
    template_name = 'home/registration_form.html'

    #display a blank form
    def get(self, request):
        form = self.form_class(None)
        return render (request, self.template_name, {'form': form})

    #process form data
    def post(self, request):
        form = self.form_class(request.POST)

        if form.is_valid():
            user = form.save(commit=False)

            #user.refresh_from_db()  # load the profile instance created by the signal
            password = form.cleaned_data['password1']
            user.set_password(password)
            username = form.cleaned_data['username']
            user.profile.birth_date = form.cleaned_data.get('birth_date')
            user.profile.location = form.cleaned_data.get('location')    
            user.save()

            #return user objects if credentials are correct
            user = authenticate(username=username, password=password)

            if user is not None:
                if user.is_active:
                    login(request, user)
                    return redirect('home:home')

        return render (request, self.template_name, {'form': form})

并且如果我取消注释注释的林斯 user.refresh_from_db()的注释,则会出现以下错误: Exception Type:DidNotExist,Exception Value:
用户匹配查询不存在.

And if I uncomment the commented lins user.refresh_from_db(), i get the following error : Exception Type: DoesNotExist, Exception Value:
User matching query does not exist.

我不确定,但是我怀疑 models.py 中的信号不能正常工作.

I'm not sure at all, but I suspect that the signals in the models.py are not working properly.

任何人都可以帮忙吗?

推荐答案

首先,您不能分配: user.profile ,因为 user 是一个实例没有此属性的用户模型.

First of all, you can't assign: user.profile, because user is an instance of the model User, which does not have this attribute.

在使用信号创建用户后,我不建议您使用此结构来创建配置文件.您最好使用用户的属性(用户名,密码,电子邮件)创建User,然后创建Profile实例.

I would not recommend this structure that you are using to create profile after creating a User using signals. You'd better create the User with its attributes (username, password, email) and then create the Profile instance.

user.save()
Profile.objects.create(
    user=user,
    location=form.cleaned_data.get('location'),
    birth_date=form.cleaned_data.get('birth_date'))

如果仍要使用信号来完成此任务,则应搜索如何通过信号传递参数".因此,您将通过字典传递location和birth_date,并使用此数据来创建个人资料.

If you still want to use signals to this task, you should search for "How to pass arguments by signals". So, you would pass location and birth_date by a dictionary and use this data to create a Profile.

这篇关于在django扩展用户模型中发布配置文件信息(用户没有配置文件)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆