user7275377
user7275377

Reputation:

Can't update data using class based view and django form

I can't update userprofile instance using django form and a class based view. POST request is send with proper parameters, template is redirecting properly, but unfortunately userprofile is not updating.

Please notice that I'm new to Django, so every tips are welcome.

models.py:

class UserProfile(models.Model):
    objects = models.Manager()
    user = models.OneToOneField(User)
    search_range = models.IntegerField(default=150)

    def __str__(self):
        return self.user.username

forms.py:

class HomeForm(forms.ModelForm):

    class Meta:
        model = UserProfile
        fields = ('search_range',)

views.py:

class HomeView(TemplateView):
    template_name = 'home/home.html'

    def get(self, request):
        form = HomeForm()

        args = {'form': form}
        return render(request, self.template_name, args)

    def post(self, request):
        form = HomeForm(request.POST, instance=request.user.userprofile)
        if form.is_valid():
            form.save()
            return redirect('home:home')

        args = {'form': form}
        return render(request, self.template_name, args)

urls.py:

urlpatterns = [
    url(r'^$', HomeView.as_view(), name='home')
]

home.html:

<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Submit</button>
</form>

Upvotes: 1

Views: 654

Answers (1)

Antoine Pinsard
Antoine Pinsard

Reputation: 34962

Your code looks good. The user profile was likely saved but, since you don't pass the instance keyword argument to the form in the get method, search_range is prefilled with the default value (150).

def get(self, request):
    form = HomeForm(instance=request.user.userprofile)

    args = {'form': form}
    return render(request, self.template_name, args)

Upvotes: 1

Related Questions