ValueError at /profile/ in Django: didn't return an HttpResponse object

StackOverflow https://stackoverflow.com/questions/23667867

  •  22-07-2023
  •  | 
  •  

سؤال

I have this line of code in models.py

 @login_required
 def user_profile(request):
    if request.method == 'POST':
        form = UserProfileForm(request.POST, instance=request.user.profile)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/accounts/loggedin')
        else:
            user = request.user
            profile = user.profile
            form = UserProfileForm(instance=profile)
            args = {}
            args.update(csrf(request))
            args['form'] = form
            return render(request, 'profile.tml', args)

and in forms.py

from django import forms
from models import UserProfile


class UserProfileForm(forms.ModelForm):
    class Meta:
        model = UserProfile
        fields = ('address', 'contactnos')

in my loggedin.html

{% extends 'base.html' %}

{% block content %}
<h2> Hi {{ full_name }} you are logged in!</h2>
<p>click <a href="/accounts/logout/">here</a> to logout. </p>

<p>Click <a href="/profile/">here</a> to edit your profile info </p>

{% endblock %}

The error is says:

ValueError at /profile/ The view userprofile.views.user_profile didn't return an HttpResponse object.

هل كانت مفيدة؟

المحلول

You haven't accounted for a GET scenario; what happens when the view is not accessed via POST? You return nothing, therefore you get this error.

Return an http.HttpResponse when request.method != 'POST'

Perhaps you meant to un-indent the bottom half else statement.

You haven't accounted for a GET scenario; what happens when the view is not accessed via POST? You return nothing, therefore you get this error.

Return an http.HttpResponse when request.method != 'POST'

Perhaps you meant to un-indent the bottom half else statement.

@login_required
 def user_profile(request):
    if request.method == 'POST':
        form = UserProfileForm(request.POST, instance=request.user.profile)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/accounts/loggedin')
    else:
        user = request.user
        profile = user.profile
        form = UserProfileForm(instance=profile)
        args = {}
        args.update(csrf(request))
        args['form'] = form
        return render(request, 'profile.tml', args)
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top