I have a form that should redirect to another view function called content to predict. I receive an error saying that the form doesn't exist when it does as shown in my code:
def content_to_predict(request):
if request.method == "POST":
form = InputForm(request.POST)
if form.is_valid():
return redirect('content_to_predict')
else:
form = InputForm()
return render(request, 'prediction/content_input.html', {'form': form})
def show_prediction_result(request):
return HttpResponse('hello')
What's the problem?
Figured it out. Instead of using redirect, just make a call to another function itself by:
return show_prediction_result(request)
I can't say one way or another as to why redirect doesn't work. If anyone has any input in regards to that. I'd appreciate it.
Related
I"ve got a simple question:
Do I need to listen for IntegrityErrors when I am already checking a submitted ModelForm's integrity with is_valid?
My code looks like this at the moment and I am thinking about removing the try catch:
def edit_object(request, object_id):
o = get_object_or_404(ObjectModel, pk=object_id)
if request.method == 'POST':
form = ObjectForm(request.POST, instance=o)
try:
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('namespace:startpage')
else:
return render(request, 'namespace/editpage.html', {'form': form,})
except IntegrityError:
return render(request, 'namespace/editpage.html', {'form': form,})
return render(request, 'namespace/editpage.html', {'form': ObjectForm(instance=o),})
Since I never even save my object if the data is not valid, I should never be able to produce an IntegrityError-exception, right?
Thanks in advance.
I have a form that I've been working on, currently displaying in a template called search_test.html, that I've finally gotten working right. I want to actually integrate it into my site, but on my site it's not going to be its own page, it's going to be a sidebar that's present on most pages. I know when I do that, this line
return render_to_response('corpus/search_test.html',
{'form': form}, context_instance=RequestContext(request))
is going to give me problems, because I don't want to actually redirect to search_test.html.
What can I replace this 'render_to_response' with, to tell it to just stay on the same page, but still pass the form info? I know this has got to be something simple, but I've looked all over online and in the docs and I can't find a similar example. (The view code for the form is below.)
Thank you.
def concord_test(request):
if request.method == 'POST': # If the form has been submitted...
form = ConcordanceForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
searchterm = form.cleaned_data['searchterm'].encode('utf-8')
search_type = form.cleaned_data['search_type']
category = form.cleaned_data['category']
context, texts_len, results_len = make_concordance(searchterm, search_type, cat=category)
return render_to_response('corpus/concord.html', locals()) # Redirect after POST
else:
form = ConcordanceForm() # An unbound form
return render_to_response('corpus/search_test.html',
{'form': form}, context_instance=RequestContext(request))
In a function page view (as per example)
you can do something like
def other_page(request):
if request.method == 'POST':
return concord_test(request)
else:
form = ConcordanceForm()
#Processing for other_page
object_list = OtherPageModel.objects.all()
return render_to_response('corpus/other_page.html',
{'form': form , 'object_list': object_list }, context_instance=RequestContext(request))
my advice: study class based views , you can have more granular capabilities dealing with 'repetitive' tasks like this & more.
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
I have a urlpattern that brings a template that allows the fields of a model instance to be viewed:
(r'^display/(?P<id>\w+)/', display_record),
I also have a view function that allows a single instance to be edited. When the object is saved, it simply returns to the same template:
if form.is_valid():
form.save()
return HttpResponseRedirect('/')
After the save, how do I return to the display template, as opposed to refreshing the same view?
the code would look something like the following but I need a way to pass the object "id" to the HttpResponse request:
def edit_record(request, id):
if request.method == 'POST':
a=ProjectRecord.objects.get(pk=id)
form = RecordForm(request.POST, instance=a)
if form.is_valid():
form.save()
return HttpResponseRedirect**('/display/(?P<id>\w+)/')**
else:
a=ProjectRecord.objects.get(pk=id)
form = RecordForm(instance=a)
return render_to_response('productionModulewire.html', {'form': form})
You're overcomplicating things. You already know what the ID is, so why can't you just put it back into the URL?
return HttpResponseRedirect('/display/%s/' % id)
or, better, since it doesn't tie you to a particular hard-coded URL:
return HttpResponseRedirect(reverse('edit_record', kwargs={'id':id}))