ailinmc
ailinmc

Reputation: 77

Edit UserProfile using Django Forms

I am creating a web application using the Django web framework. As part of the application, I wanted to give users the ability to update their profile as they choose. When a user tries to update their profile however, the information remains the same even after the user has submitted new information. I've checked my database and the values are not being updated in there either. It is possible however, to change a Users information on the admin page. Below is how I have tried to implement the functionality.

Model

class UserProfileModel(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    age = models.PositiveIntegerField(blank=True, null=True)
    email = models.EmailField(max_length=254, null=True, blank=True, unique=True)
    height = models.PositiveIntegerField(blank=True, null=True)
    weight = models.PositiveIntegerField(blank=True, null=True)

Form

class UpdateProfile(forms.ModelForm):

    class Meta:
        model = UserProfileModel
        fields = ('email', 'age', 'height', 'weight')

Views

def update_profile(request):
    args = {}

    if request.method == 'POST':
        form = UpdateProfile(request.POST, instance=request.user)
        if form.is_valid():
            form.save()
            # return HttpResponseRedirect(reverse('account:profile'))
            return render(request, 'account/profile.html')
    else:
        form = UpdateProfile()
        if request.user.is_authenticated():
            form = UpdateProfile(instance=request.user)
        args['form'] = form
        return render(request, 'account/edit_profile.html', args)

Url

app_name = 'account'
urlpatterns = [
    url(r'^profile/$', views.profile, name='profile'),
    url(r'^profile/edit/$', views.update_profile, name='edit_profile'),
    url(r'^home/$', views.home, name='home'),

]

HTML

{% block body %}
    <div class="container">
        <form method="POST" action=".">
            {% csrf_token %}
            {{ form.as_p }}
            <button type="submit">Submit</button>
        </form>
        <br>
    </div>
{% endblock %}

Upvotes: 1

Views: 43

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 600051

Your form is not for a User, it is for a UserProfileModel (which by the way is an odd name; there's no need to include the word "model" there).

So you should pass the profile, not the user, to the form:

form = UpdateProfile(request.POST, instance=request.user.userprofilemodel)

Note, you probably also want to pass it in the else block, so that the user sees the existing data to edit on GET:

form = UpdateProfile(instance=request.user.userprofilemodel)

Also, you should redirect after successful POST, as you do in the commented-out line, rather than rendering a template.

Upvotes: 2

Related Questions