Django didn't return an HttpResponse object - django

I made a simple pet store app and just added search box feature and I received this error
ValueError at /pet/search/
The view mysite.pet.views.search_page didn't return an HttpResponse object.
I tried to change render_to_response into HttpResponseRedirect but still got the same error.
Linking back to my search_page function in views.
def search_page(request):
form = SearchForm()
if request.method == "POST":
f = SearchForm(request.POST)
if f.is_valid():
Pets = Pet.objects.filter(animal = f.cleaned_data["text"])
return HttpResponseRedirect("search.html",{"Pets":Pets},{"form":form})
else:
return render_to_response("search.html",{"form":form} , context_instance = RequestContext(request))
I did some research and I understand a view has to return a HttpResponse when a HttpRequest is made and render_to_response is just a shortcut.Can someone help explain why this function won't work.Thank you

You are getting this problem because you havn't written a HttpResponse object if request type is not POST
To overcome this in your view write somthing which will process if request type is not post
def search_page(request):
form = SearchForm()
if request.method == "POST":
f = SearchForm(request.POST)
if f.is_valid():
Pets = Pet.objects.filter(animal = f.cleaned_data["text"])
return HttpResponseRedirect("search.html",{"Pets":Pets},{"form":form})
return render_to_response("search.html",{"form":form} , context_instance = RequestContext(request))
Hope this will help you thanks

The error is because when the function is called the method type is not POST and it does not find the corresponding HttpResponse object.
def search_page(request):
form = SearchForm()
if request.method == "POST":
f = SearchForm(request.POST)
if f.is_valid():
Pets = Pet.objects.filter(animal = f.cleaned_data["text"])
return HttpResponseRedirect("search.html",{"Pets":Pets},{"form":form})
else:
return render_to_response("search.html",{"form":form} , context_instance = RequestContext(request))
return render_to_response("any.html",{} , context_instance = RequestContext(request))

def addsponser(request):
if request.method == 'POST':
# return HttpResponse(request,'error is here')
if (request.POST.get('firstname') and
request.POST.get('lastname') and
request.POST.get(' email') and
request.POST.get('phone_Number') and
request.POST.get('gender') and
request.POST.get('state') and
request.POST.get('adress') and
request.POST.get('postal_code') and
request.POST.get('town')
):
fname = request.POST.get('firstname')
lname = request.POST.get('lastname')
em = request.POST.get(' email')
phn = request.POST.get('phone_Number')
gnd = request.POST.get('gender')
stt = request.POST.get('state')
add = request.POST.get('adress')
pstc = request.POST.get('postal_code')
twn = request.POST.get('town')
try:
sponser = Sponsers()
sponser.firstname = fname
sponser.lastname = lname
sponser.email = em
sponser.Phone_Number = phn
sponser.gender = gnd
sponser.state = stt
sponser.adress = add
sponser.postal_code = pstc
sponser.town = twn
sponser.save()
messages.success(request, "sponser Added")
return redirect('sponsers')
except Exception:
messages.error(request, "Failed to add sponser")
return redirect('sponsers')
else:
pass
else:
return redirect('sponsers')

Related

Django how to check if user is in path

I made an unique url and I want to check if the acutal url contains the uid so I made a if statement which is always false in my case so what can I change that it works and checks if the path contains the uid.
views.py
#login_required(login_url='home:login')
def ChangeEmailView(request, token):
packet = get_object_or_404(TempUrl, user=request.user)
token = packet.uid
if request.path == str(token):
if request.method == 'POST':
objects = User.objects.get(email = request.user.email)
form = EmailChangingForm(request.POST, instance=objects)
if form.is_valid():
form.save()
return redirect('home:profilesettings')
else:
objects = User.objects.get(email = request.user.email)
form = EmailChangingForm(request.POST, instance=objects)
packet = get_object_or_404(TempUrl, user=request.user)
token = packet.uid
else:
print('site wasnt found')
objects = User.objects.get(email = request.user.email)
form = EmailChangingForm(request.POST, instance=objects)
packet = get_object_or_404(TempUrl, user=request.user)
token = packet.uid
return redirect('home:index')
context = {'form': form, 'token': token}
return render(request, 'home/email_settings.html', context)
Given that URL bound to ChangeEmailView was set by
path('settings/email/changeemail/<str:token>', views.ChangeEmailView , name="changeemail")
then if request.path == str(token) is always False because request.path includes full URL path (i.e. /settings/email/changeemail/) not just your token.
I think you want the following
#login_required(login_url='home:login')
def ChangeEmailView(request, token):
packet = get_object_or_404(TempUrl, user=request.user)
site_token = packet.uid
if token == str(site_token):
if request.method == 'POST':
objects = User.objects.get(email = request.user.email)
form = EmailChangingForm(request.POST, instance=objects)
if form.is_valid():
form.save()
return redirect('home:profilesettings')
else:
objects = User.objects.get(email = request.user.email)
form = EmailChangingForm(request.POST, instance=objects)
packet = get_object_or_404(TempUrl, user=request.user)
token = packet.uid
else:
print('site wasnt found')
objects = User.objects.get(email = request.user.email)
form = EmailChangingForm(request.POST, instance=objects)
packet = get_object_or_404(TempUrl, user=request.user)
token = packet.uid
return redirect('home:index')
context = {'form': form, 'token': token}
return render(request, 'home/email_settings.html', context)
Django will extract last entry of URL path and pass to your view as the token parameter, you can just use that to check if your uid is present.

inserting a lot of data via create_bulk

hello I have a table named Exercise data where I pass data from form and save them in the db, my problem is that I have more same objects to save inside the db but I don't know how to do it.
I left you my views.py file where you can find the code I created.
I read around that I should use the create_bulk but I don't understand how I can pass it some data from my form, could someone help me please? =)
views.py
#login_required
def creaScheda(request):
if request.method == "POST":
form = CreaSchedaForm(request.POST)
if form.is_valid():
schedaName = form.cleaned_data['nome_scheda']
scheda = form.save(commit = False)
scheda.utente = request.user
scheda.save()
gruppi = DatiGruppi(
giorni_settimana = form.cleaned_data['giorni_settimana'],
dati_gruppo = form.cleaned_data['dati_gruppo'],
gruppi_scheda = Schede.objects.get(nome_scheda = schedaName)
)
gruppi.save()
esercizi = DatiEsercizi(
serie = form.cleaned_data['serie'],
ripetizione = form.cleaned_data['ripetizione'],
peso = form.cleaned_data['peso'],
gruppo_single = DatiGruppi.objects.get(gruppi_scheda = scheda.id),
dati_esercizio = form.cleaned_data['dati_esercizio']
)
#esercizi.save()
print(esercizi)
return redirect('/backoffice')
else:
form = CreaSchedaForm()
context = {"form": form}
return render(request, "crea_scheda.html", context)

I am getting object has no attribute update in my Django Website

I have a crud application and would like to update the items. I have checked some solutions online which explains that the .update method can't be used like this but for only a queryset. I don't know how to update the information manually. Thanks
views.py
def UpdateReservation(request, pk):
table_exists = Reservation.objects.get(id=pk)
form = ReservationForm(instance=table_exists)
if request.method == "POST":
if request.POST['table']:
request.POST = request.POST.copy()
table_exists = Reservation.objects.get(id=pk)
try:
if table_exists:
time = form['time']
people = form['people']
comment = form['comment']
date_reserved = form['date_reserved']
email = form['email']
phone = form['phone']
first_name = form['first_name']
resrv = table_exists.update(email=email, first_name=first_name, people=people, time=time, date_reserved=date_reserved, comment=comment, table=table_exists)
resrv.save()
messages.success(request, "you have successfully edited.")
return redirect(request.path)
else:
messages.error(request, "Unable to edit.")
return redirect(request.path)
except Exception as e:
messages.error(request, "Unknown error" + str(e))
return redirect(request.path)
context = {"form":form}
return render(request, "dashboard/super/admin/update_reserve.html", context)
After trying that, it returns the error, Unknown error'Reservation' object has no attribute 'update'
It is better to validate the form and update the individual fields with respective values and then save the object. The view should be as follows:
from django.shortcuts import get_object_or_404
def UpdateReservation(request, pk):
table_exists = get_object_or_404(Reservation, id=pk)
form = ReservationForm(instance=table_exists)
if request.method == "POST":
form = ReservationForm(request.POST, instance=table_exists)
if form.is_valid():
time = form['time']
people = form['people']
comment = form['comment']
date_reserved = form['date_reserved']
email = form['email']
phone = form['phone']
first_name = form['first_name']
table_exists.email = email
table_exists.first_name = first_name
table_exists.people = people
table_exists.time = time
table_exists.date_reserved = date_reserved
table_exists.comment = comment
table_exists.save()
messages.success(request, "you have successfully edited.")
return redirect(request.path)
else:
messages.error(request, "Unable to edit.")
return redirect(request.path)
context = {"form": form}
return render(request, "dashboard/super/admin/update_reserve.html", context)
You should use model like this:
table_exists = Reservation.objects.get(id=pk)
table_exists.email = email
table_exists.first_name = first_name
table_exists.people = people
table_exists.time = time
table_exists.date_reserved = date_reserved
table_exists.comment = comment
table_exists.table = table_exists
table_exists.save()

the view didn't return an HttpResponse object. It returned None

For testing my form loggin, in the view index I return a dictionary. When I clicked on the submit button I receive this message error :
The view accueil.views.index didn't return an HttpResponse object. It returned None instead.
Where I made a mistake?
def index(request):
formConnex = ConnexionForm()
if request.method=='POST':
formConnex =ConnexionForm(request.POST)
if formConnex.is_valid():
envoi = True
surnom = formConnex.cleaned_data['surnom']
password = formConnex.cleaned_data['passeword']
formConnex = ConnexionForm()
dicInfoCon = {
'surnom_key':email,
'password_key':password,
'envoi_key':envoi
}
return render(request,'accueil/index.html',dicInfoCon)
else:
envoi = False
formConnex = ConnexionForm()
return render(request, 'accueil/index.html', 'formConnex_Key':formConnex})
The problem is simply that your final return line is indented too far. Move it back one indent, so that it also catches the case where request is POST but the form is not valid.
The problem is when the form is not valid. It does not return anything from function. To be exact:
if request.method=='POST':
formConnex =ConnexionForm(request.POST) # Please use snake_case
if formConnex.is_valid():
envoi = True
surnom = formConnex.cleaned_data['surnom']
password = formConnex.cleaned_data['passeword']
formConnex = ConnexionForm()
dicInfoCon = {
'surnom_key':email,
'password_key':password,
'envoi_key':envoi
}
return render(request,'accueil/index.html',dicInfoCon)
# Here should be an else block with how the view should handle if the form is not valid
So, you can update the method like this(I have added some refactoring):
def index(request):
formConnex = ConnexionForm(request.POST or None) # Please use snake_case, according to PEP-8 style guide
if request.method == 'POST':
if formConnex.is_valid():
envoi = True
surnom = formConnex.cleaned_data['surnom']
password = formConnex.cleaned_data['passeword']
dicInfoCon = {
'surnom_key': email,
'password_key': password,
'envoi_key': envoi
}
return render(request, 'accueil/index.html', dicInfoCon)
return render(request, 'accueil/index.html', {'formConnex_Key':formConnex})

Why my code does not show validation form error message?

Why my code does not show validation form error message?
I try something like this:
def index(request):
if request.method == "POST":
if request.POST['form-type'] == 'contact-form':
form = AngebotForm(None, request.POST)
if form.is_valid():
form.save()
msg = 'Good!'
return render_to_response('index.html',{'msg':msg}, context_instance=RequestContext(request))
else:
form = AngebotForm()
else:
form = MessageForm(request.POST)
if form.is_valid():
form.save()
msg = 'Good!'
return render_to_response('index.html',{'msg':msg},context_instance=RequestContext(request))
else:
form = MessageForm()
return render_to_response('index.html',{'a_form':AngebotForm(), 'm_form':MessageForm()},context_instance=RequestContext(request))
What am I doing wrong?
Because in else part you are re-initializing the form which will loose the current state of form.
Just remove these lines:
else:
form = MessageForm()
In the end your view should look like this:
def index(request):
form = AngebotForm()
m_form = MessageForm()
if request.method == "POST":
if request.POST['form-type'] == 'contact-form':
form = AngebotForm(None, request.POST)
if form.is_valid():
form.save()
msg = 'Good!'
return render_to_response('index.html',{'msg':msg}, context_instance=RequestContext(request))
else:
m_form = MessageForm(request.POST)
if m_form.is_valid():
m_form.save()
msg = 'Good!'
return render_to_response('index.html',{'msg':msg},context_instance=RequestContext(request))
return render_to_response('index.html',{'a_form':form, 'm_form':m_form},context_instance=RequestContext(request))