问题
i created userProfile for some additional user information. here my model:
class UserProfile(models.Model):
user = models.OneToOneField(User)
picture = models.ImageField(upload_to=get_upload_path, blank=True)
def __unicode__(self):
return self.user.username
def create_user_profile(sender, **kwargs):
u = kwargs["instance"]
if not UserProfile.objects.filter(user=u):
UserProfile(user=u).save()
post_save.connect(create_user_profile, sender=User)
I need settings page and in this page i will update some fields of user and user profile fields at the same time. Here my forms:
class UpdateUserForm(ModelForm):
class Meta:
model = User
fields = ['first_name', 'last_name']
class UpdateUserProfileForm(ModelForm):
class Meta:
model = UserProfile
exclude = ['user']
i have one form in my template and related function is:
def post(self, request, *args, **kwargs):
update_user_form = UpdateUserForm(data=request.POST, instance=request.user)
update_user_profile_form = UpdateUserProfileForm(data=request.POST)
if update_user_form.is_valid() and update_user_profile_form.is_valid():
user = update_user_form.save()
userProfile = update_user_profile_form.save(commit=False)
userProfile.user = user
userProfile.save()
in this case i am getting "column user_id is not unique" error. why this is trying to add new user profile with this user?
what is best practice for this case?
thank you
回答1:
I had the same problem a while ago. In the end I opted to change my custom user model to make it inherit from AbstractUser (more info on this here: https://docs.djangoproject.com/en/dev/topics/auth/customizing/) instead of linking it to User with a onetoonefield:
models.py:
class CustomUser(AbstractUser):
picture = models.ImageField(upload_to=get_upload_path, blank=True)
views.py:
class UpdateUser(LoginRequiredMixin, UpdateView):
model = CustomUser
fields = ('first_name', 'last_name', 'picture')
template_name = 'user/edit.html'
success_url = reverse_lazy('forum:top')
来源:https://stackoverflow.com/questions/26361142/update-user-and-user-profile-on-same-form