I m facing error in Django :invalid syntax (views.py).
def deals(request):
form = deals()
if request.method == "POST":
form = deals(request.POST, request.FILES)
if form.is_valid():
form.save()
else:
return render_to_response("deals.html", {'form':form}, context_instance=RequestContext(request))
else:
form = deals()
return render_to_response("deals.html", {'form':form}, context_instance=RequestContext(request))
The problem is actually an issue with indentation, which manifests as a syntax error. The four lines beginning if form.is_valid() should be indented one level.
However, this would still not be the recommended pattern. You don't need the inner else at all, and you must redirect after a successful post.
def deals(request):
form = DealsForm()
if request.method == "POST":
form = DealsForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('/') # or wherever
else:
form = DealsForm()
return render(request "deals.html", {'form':form})
Also I've used the render shortcut instead of render_to_response, as that uses a RequestContext automatically.
Note that all this is explicitly given in the docs; there's no reason to do anything else.
Related
I have a view function that resubmits data when I refresh the page.
def home(request):
if request.method == 'POST':
form = ListForm(request.POST or None)
if form.is_valid():
form.save()
all_items = List.objects.all
messages.success(request,('Item has been added to List'))
return render(request, 'home.html', {'all_items': all_items})
else:
all_items = List.objects.all
return render(request, 'home.html',{'all_items':all_items})
Any ideas on how to prevent this please. render_to_response is now deprecated from what Ive read.
Thank you
Preventing form resubmission is nothing new, the canonical solution is the post-redirect-get pattern: after a successful post, you return a redirect HTTP response, forcing the user's browser to do a get. The canonical Django "form handler" view (in it's function version) is:
def yourview(request):
if request.method == "POST":
form = YourForm(request.POST)
if form.is_valid():
do_something_with_the_form_data_here()
return redirect("your_view_name")
# if the form isn't valid we want to redisplay it with
# the validation errors, so we just let the execution
# flow continue...
else:
form = YourForm()
# here `form` will be either an unbound form (if it's a GET
# request) or a bound form with validation errors.
return render(request, "yourtemplate.html", {'form': form, ...})
My "view" code has an obvious repetition in its code. Is there any way of refactoring the "return" code?
def form_contractor_view(request):
if request.method == 'POST':
form = ContractorForm(request.POST)
if form.is_valid():
form.save()
return redirect('index_view')
else:
return render_to_response(
'form_contractor.html',
{'form': form},
context_instance=RequestContext(request),
)
else:
form = ContractorForm()
return render_to_response(
'form_contractor.html',
{'form': form},
context_instance=RequestContext(request),
)
There is no need for the first else at all. Move the final render back an indent, and that will catch the else case. Note that this is the pattern explicitly described in the documentation.
Also, use render instead of render_to_response.
def form_contractor_view(request):
if request.method == 'POST':
form = ContractorForm(request.POST)
if form.is_valid():
form.save()
return redirect('index_view')
else:
form = ContractorForm()
return render(
request,
'form_contractor.html',
{'form': form},
)
I will give my try:
def form_contractor_view(request):
form = ContractorForm(request.POST or None)
if form.is_valid():
form.save()
return redirect(reverse('index_view')) # <-- you forgot reverse() here
return render(
request,
'form_contractor.html',
{'form': form}
)
I replaced render_to_response with render which does the same thing - you just type less... try to be lazy ;)
I think, this works. not tested though. If request is not done in POST, then is_valid() returns False returning the form as None back again which makes sense. and for the case where the request is done in POST and invalid values in it, then else kicks in and returns the form with error messages... I think, this works.. please test
I'm pretty new to Python so that may be a stupid question but I'll ask it anyway. Is there a Django forms "design pattern" for this common view situation? When I run the view, I want it to act on one of two different types of forms depending on the type of user who's filling out the form. It seems ugly to have two if/then blocks inside the if request.method block to determine which type of form I'm acting on. What I'd like is to be able to refer to a "CreateProfileForm" that will refer to either a CreateManProfileForm or CreateWomanProfileForm depending on what's in the session variable.
Thanks!
def create_profile(request, template):
if request.session['user_type_cd'] == 'man':
is_man = True
else:
is_man = False
if request.method == "POST":
if is_man:
form = CreateManProfileForm(request.POST)
else:
form = CreateWomanProfileForm(request.POST)
if form.is_valid():
# Do stuff
return HttpResponseRedirect(reverse('do-next-thing'))
else:
if is_man:
form = CreateManProfileForm()
else:
form = CreateWomanProfileForm()
return render_to_response(template, locals(), context_instance=RequestContext(request))
You can do something like this:
Create a dictionary of the forms,
FORMS = {
0: CreateWomanProfileForm,
1: CreateManProfileForm
}
And in the views:
def create_profile(request, template):
is_man = 1 if request.session.get('user_type_cd') == 'man' else 0
if request.method == "POST":
form = FORMS.get(is_man)(request.POST)
if form.is_valid():
# Do stuff
return HttpResponseRedirect(reverse('do-next-thing'))
else:
form = FORMS.get(is_man)()
return render_to_response(template, locals(), context_instance=RequestContext(request))
Or even this should work
def create_profile(request, template):
is_man = 1 if request.session['user_type_cd'] == 'man' else 0
form = FORMS.get(is_man)(request.POST or None)
if request.method == "POST":
if form.is_valid():
# Do stuff
return HttpResponseRedirect(reverse('do-next-thing'))
return render_to_response(template, locals(), context_instance=RequestContext(request))
I've used Django forms. I have this function in views.py:
def func(request):
if request.method == "POST":
form = MyForm(request.POST)
if form.is_valid():
//do processing
return HttpResponseRedirect('/')
else:
form = MyForm()
return render_to_response("checkbox.html", RequestContext(request, {'form':form}))
but when form is invalid, it shows me the error: The view didn't return an HttpResponse object. I've searched and realized every where the view functions are like this, but I don't know why mine has error. It seems it doesn't know what to do, while form in invalid!!! Why it doesn't show the page and show user the form errors? can you please help me?
When the form is invalid, the view just returns since else part of the if statement is only evaluated when the request.method == "POST" is False, which it is not...
To fix this, the following is the usual pattern for making form views:
def func(request):
if request.method == "POST":
form = MyForm(request.POST)
if form.is_valid():
//do processing
return HttpResponseRedirect('/')
else:
form = MyForm()
# outside of the else clause
# if the form is invalid, then it will also show the error messages to the user
return render_to_response("checkbox.html", RequestContext(request, {'form':form}))
You already have your answer on #miki725 post. Just a suggestion you might want to consider GET as the default behaviour to avoid those if .. else:
def func(request):
# GET is the default behaviour
form = MyForm()
if request.method == "POST":
form = MyForm(request.POST)
if form.is_valid():
//do processing
return HttpResponseRedirect('/')
return render_to_response("checkbox.html", RequestContext(request, {'form':form}))
I have a simple view in which I'm saving a form. The code seems 'clean', but I can't get rid of the error:
"The view didn't return an HttpResponse object."
Though I've searched on the web, I did not find a relevant indication.
def classroom_privacy(request,classname):
theclass = Classroom.objects.get(classname=classname)
if request.method == 'POST':
form = PrivacyClass(request.POST)
if form.is_valid():
new_obj = form.save(commit=False)
new_obj.save()
return HttpResponseRedirect('.')
else:
form = PrivacyClass()
return render_to_response('classroom/classroom_privacy.html', {'form': form},
context_instance=RequestContext(request))
verify the indentation of your code
def classroom_privacy(request, classname):
theclass = Classroom.objects.get(classname=classname)
if request.method == 'POST':
form = PrivacyClass(request.POST)
if form.is_valid():
new_obj = form.save(commit=False)
new_obj.save()
return HttpResponseRedirect('.')
else:
form = PrivacyClass()
return render_to_response('classroom/classroom_privacy.html', {'form': form}, context_instance=RequestContext(request))
if it is get request, render a unbound form
if it is post request and invalid form render a bound form
if it is post request and valid form redirect the page
All view functions must return some kind of HttpResponse object. There exists a code path in your function where None will be returned instead. This will occur when request.method != 'POST' and you'll simply "fall off the end" of your function (which will return None).
If you are using the Django Rest framework. Use the below code to return the HTTP response to resolve this issue.
from django.http import HttpResponse
def TestAPI(request):
# some logic
return HttpResponse('Hello')
JSON Response return example:
def TestAPI(request):
your_json = [{'key1': value, 'key2': value}]
return HttpResponse(your_json, 'application/json')
For more details about HttpResponse:
https://docs.djangoproject.com/en/3.1/ref/request-response/#django.http.HttpResponse