matching query does not exist - django

I'm trying to catch an exception but does not work.This is the code in my view:
#login_required
def activities_edit(request, edit):
ActivityFormSet = modelformset_factory(Activity, can_delete=True)
act_edit= Activity.objects.filter(campaing=1).get(pk=edit)
try:
if act_edit:
if request.method == 'POST':
formset = ActivityFormSet(request.POST, request.FILES, queryset=Activity.objects.filter(pk=edit))
if formset.is_valid():
formset.save()
return HttpResponseRedirect('/activities/')
else:
formset = ActivityFormSet(queryset=Activity.objects.filter(pk=edit))
except act_edit.DoesNotExist:
return HttpResponseRedirect('/activities/')
I was also trying with: " except act_edit.DoesNotExist: "
but the error persists "Activity matching query does not exist."
Any idea?
Thanks!

You need to move the statement that can cause the exception in the body of the try: clause.
The syntax is "try: something catch stuff:" your something is above the try:
act_edit= Activity.objects.filter(campaing=1).get(pk=edit)
try:
Should be
try:
act_edit = Activity.objects.filter(campaing=1).get(pk=edit)

You have a little bit of redundancy catching the exception means you don't have to check if act_edit is empty because if it is empty it will raise DoesNotExist. Also the model has the DoesNotExist not the instance.
#login_required
def activities_edit(request, edit):
ActivityFormSet = modelformset_factory(Activity, can_delete=True)
try:
act_edit= Activity.objects.filter(campaing=1).get(pk=edit)
if request.method == 'POST':
formset = ActivityFormSet(request.POST, request.FILES, queryset=Activity.objects.filter(pk=edit))
if formset.is_valid():
formset.save()
return HttpResponseRedirect('/activities/')
else:
formset = ActivityFormSet(queryset=Activity.objects.filter(pk=edit))
#HttpResponse not returned error here.
except Activity.DoesNotExist:
return HttpResponseRedirect('/activities/')

Related

invalid syntax in view.py in django.?

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.

The view didn't return an HttpResponse object error when form is not valid: django

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}))

django - how to check if model is empty

I have settings form page. If user filled the form once; it must display those values. But if there is no data [first time] I get query error. I need that query, because the form data must be written as related with current user [logged in].
here is my view part :
#login_required(login_url='/login/')
def profile_page(request,username):
query = Profile.objects.get(owner__username = username) ##error!
if request.method == 'POST':
form = profile_form(request.POST,instance=query)
form.save()
return HttpResponseRedirect('/admin/')
else:
form = profile_form(instance=query)
return render_to_response('profile_save.html',{'form':form},context_instance = RequestContext(request))
I think I need to check the model and if it is empty I should do something different.
I am stuck.
Thank you
You want to make use of the .exists() queryset option
#login_required(login_url='/login/')
def profile_page(request,username):
form = profile_form()
if Profile.objects.get(owner__username = username).exists():
query = Profile.objects.get(owner__username = username)
if request.method == 'POST':
form = profile_form(request.POST,instance=query)
form.save()
return HttpResponseRedirect('/admin/')
else:
form = profile_form(instance=query)
return render_to_response('profile_save.html',{'form':form},context_instance = RequestContext(request))
see QuerytSet API reference for more information
You just need to wrap that get query in try ... except and set instance to none, like this.
from django.core.exceptions import ObjectDoesNotExist
#login_required(login_url='/login/')
def profile_page(request,username):
try:
query = Profile.objects.get(owner__username = username)
#to be more specific you can except ProfileObjectDoesNotExist
except ObjectDoesNotExist:
query = None #Doesn't exist, set to None
if request.method == 'POST':
form = profile_form(request.POST,instance=query)
form.save()
return HttpResponseRedirect('/admin/')
else:
form = profile_form(instance=query)
return render_to_response('profile_save.html',{'form':form},
context_instance = RequestContext(request))
I think i may have use get_or_create for this purpose.
Profile.objects.get_or_create(owner__username = username)

Try/except database query in django

I am checking a user's submitted email address against two lists from the database -- a list of authorized domains and a list of authorized email addresses. Currently, if neither are found, it is rainsing a DoesNotExist exception. How would I handle this if neither are found?
Here is the code I currently have in views.py --
def register(request):
if request.method == 'POST':
form = UserForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
try:
email_list = EmailList.objects.get(domain=(cd['email'].split('#')[1]))
except:
email_list = EmailList.objects.get(email=cd['email'])
# I also need another except if neither works for the validator.
network= Network.objects.get(network=email_list.network)
User.objects.create(name=cd['name'], email=cd['email'], network=network)
return HttpResponseRedirect ('/user/view/')
else:
form = UserForm()
return render_to_response('register.html',{'form':form}, context_instance = RequestContext(request))
Nested try/except blocks. And don't use a bare except; catch only the exceptions you can handle.
You can nest try/except:
try:
email_list = EmailList.objects.get(domain=(cd['email'].split('#')[1]))
except:
try:
email_list = EmailList.objects.get(email=cd['email'])
except:
...do something else
If you are just using these try/except to do a simple test, it's worthwhile to wrap the try/except:
def get_or_none(model, **kwargs):
try:
return model.objects.get(**kwargs)
except model.DoesNotExist:
return None
Which gives you slightly more readable code:
if get_or_none(EmailList, domain='domain.com'):
...do something
elif get_or_none(EmailList, domain='domain.com'):
...do something
else:
...do something
As Ignacio mentioned in his answer you should always be explicit and catch only the exceptions you intend.

Django "The view didn't return an HttpResponse object."

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