Reputation: 555
I have a custom user model I made, I am trying to make a form that will update it when submitted. I have looked at other answers on SO and have tried their solutions, even if my code is almost identical it will not work properly. I am getting no errors at all when I run this. The form shouldn't create a new UserAddress, but it should update its field.
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})
Upvotes: 0
Views: 266
Reputation: 600059
The form model is UserAddress, but you are passing request.user
, which is an instance of User. You should pass the related address object:
form = YourAddressForm(request.POST, instance=request.user.user_address)
(And the same in the GET block.)
Upvotes: 1