Sumit Jha
Sumit Jha

Reputation: 2195

ModelForm not saving data into the model

I have looked at all similar questions but none of them seem to help.

This is my POST method inside class ProfileEditView(generic.DetailView):

def post(self, request, *args, **kwargs):
    profile_id = kwargs.get('pk')
    user_detail = User.objects.get(id=profile_id)

    form  = EditProfileForm(request.POST, request.FILES, instance=user_detail)
    if form.is_valid():
        updated = form.save(commit=False)
        updated.phone = form.cleaned_data["phone"]
        updated.address = form.cleaned_data["address"]
        updated.gender = form.cleaned_data["gender"]
        updated.save()
        messages.success(request, "Profile details updated.")
        return redirect("profileview", profile_id)
    else:
        context = {}
        context["form"] = form
        context["profile_id"] = kwargs["pk"]
        return render(request, self.template_name, context)

Template:

<form enctype="multipart/form-data" method="POST" action="{% url 'profile_edit_view' profile_id %}">
{% csrf_token %}

{{form|crispy}}

<input type="submit" value="Save">

</form>

Models.py

class UserDetail(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL)
    profile_picture = models.FileField(upload_to=profile_image_upload, null=True, blank=True)

    phone = models.CharField(max_length=10)
    address = models.CharField(max_length=1000)
    gender = models.CharField(max_length = 10, choices=gender_choices)

Upvotes: 0

Views: 517

Answers (1)

Alasdair
Alasdair

Reputation: 309099

If EditProfileForm is editing the UserDetail, then instance should be a UserDetail instance. You are currently passing the user instead. Try changing it to:

def post(self, request, *args, **kwargs):
    user_id = kwargs.get('pk')
    user_detail = User.objects.get(id=user_id)
    user_detail = user.userdetail

    form  = EditProfileForm(request.POST, request.FILES, instance=user_detail)

Upvotes: 1

Related Questions