使用表单Django更新自定义用户模型

时间:2018-05-12 19:41:11

标签: python django

我制作了自定义用户模型,我正在尝试创建一个在提交时会更新它的表单。我已经在SO上查看了其他答案,并尝试了他们的解决方案,即使我的代码几乎相同,也无法正常工作。 我运行时没有任何错误。表单不应创建新的UserAddress,但应更新其字段。

models.py

class UserAddress(models.Model):

    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='user_address')
    your_address = models.CharField(max_length=300, blank=True, default=' ')

#used in sign up
@receiver(post_save, sender=User)
def create_user_address(sender, instance, created, **kwargs):
    if created:
        UserAddress.objects.create(user=instance)


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

forms.py

class YourAddressForm(forms.ModelForm):
    class Meta:
        model = UserAddress
        fields = ('your_address', )

views.py

@login_required()
def settings(request):
    if request.method == 'POST':
        form = YourAddressForm(request.POST, instance=request.user)
        if form.is_valid():
            form.save()
            return HttpResponse('Awesome, I added it!')
        else:
            return HttpResponse("Not added")
    else:
        form = YourAddressForm(instance=request.user)

    return render(request, 'details/settings.html', {'form': form})

1 个答案:

答案 0 :(得分:1)

表单模型是UserAddress,但您传递的是request.user,它是User的一个实例。您应该传递相关的地址对象:

form = YourAddressForm(request.POST, instance=request.user.user_address)

(在GET块中也一样。)