下面是基于createprofileview类的视图,用于注册新用户并同时创建该用户的个人资料。
class CreateProfileView(CreateView):
model = Profile
def post(self, request):
user_form = UserForm(request.POST)
profile_form = ProfileForm(request.POST, request.FILES)
if user_form.is_valid() and profile_form.is_valid():
user_form.save()
return HttpResponseRedirect(reverse('home', args=[]))
messages.warning(request, 'Something went wrong in Venter, please try again')
def get(self, request):
user_form = UserForm()
profile_form = ProfileForm()
return render(request, './mysite/registration.html', {'user_form': user_form, 'profile_form': profile_form})
我已将post_save()信号与我的Profile模型一起使用,如下所示:
class Profile(models.Model):
user = models.OneToOneField(
User,
on_delete=models.CASCADE,
primary_key = True
)
organisation_name = models.ForeignKey(
Organisation,
on_delete= models.CASCADE,
null=True,
)
profile_picture = models.ImageField(
upload_to='Organisation/Employee Profile Picture/%Y/%m/%d/',
null=True,
blank=True,
)
phone_number = models.CharField(
blank=True,
max_length=10
)
def __str__(self):
return self.user.username
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.profile.save()
但是,已创建并保存了用户,但未保存其个人资料详细信息。 我不确定如何调整信号功能以适应我注册新用户并同时创建其个人资料的要求。
请帮助!谢谢。
这是表格。py:
class UserForm(forms.ModelForm):
class Meta:
model = User
fields = ('username', 'password', 'email', 'first_name', 'last_name')
class ProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = ('organisation_name', 'phone_number', 'profile_picture')
答案 0 :(得分:1)
我看不到发出配置文件创建信号的意义,因为您已经有了FeedbackManager.showFeedbackActivity(this, Uri.fromFile(file))
来获取配置文件数据。我认为您可以摆脱配置文件信号并更新视图以直接保存配置文件表单。像这样:
https://stackoverflow.com/questions/30681918/nullpointerexception-with-actionbar-setdisplayhomeasupenabledboolean-on-a-nu
来自评论
您需要在User对象中设置密码。您可以通过这样的覆盖(使用set_password方法)在表单的ProfileForm
方法中做到这一点:
if user_form.is_valid() and profile_form.is_valid():
user = user_form.save()
profile = profile_form.save(commit=False)
profile.user = user
profile.save()
# rest of the code