Why my code does not show validation form error message? - django

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

Related

Django: change TextField before save

This is my model :
class Card(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
imp_id = models.TextField(null = True)
And here is my view :
def Add(request):
if request.method == 'POST':
form = Add_card(request.POST)
if form.is_valid():
save = form.save(commit = False)
save.user = request.user
save.imp_id = "asd" # I tried to change it here but I failed
save.save()
else:
form = Add_card()
cards = Card.objects.all()
return render(request, 'addcard.html', {'form': form, 'cards' : cards})
How can I change that textfield before save?
you can do it like this
def Add(request):
if request.method == 'POST':
request.POST.imp_id="asd"
form = Add_card(request.POST)
if form.is_valid():
save = form.save(commit = False)
save.user = request.user
save.save()
else:
form = Add_card()
cards = Card.objects.all()
return render(request, 'addcard.html', {'form': form, 'cards' : cards})
The problem could be solved by using default='asd'.

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.

Form values are not overwritten when changed - they are stuck at their default values

I have the following view:
#login_required
def my_view(request):
instance = my_model(user=request.user)
form = my_model_form(request.POST,instance = instance)
if request.method == "POST":
if form.is_valid():
form.save(commit=False)
#Field1 and field2 is already in the form (its the input)
# Do some back-end operations to get values for the remaining fields
df = some_util_function()
form.field3 = df["field3"]
form.field4 = df["field4"]
form.field5= df["field5"]
form.save()
return redirect("my_html")
else:
form = my_model_form()
context = {
"form":form
}
return render(request, "discounttracker/my_html.html",context=context)
and the problem is that field3,field4,field5 are not changed. I have even tried to hard-code them to 1000, 2000,3000 (they are FloatField(default=0)) but they remain at their default value when written to the DB.
What am I doing wrong here?
You are setting the attributes of the form, not of the instance wrapped in the form. You should alter this to:
#login_required
def my_view(request):
instance = my_model(user=request.user)
if request.method == 'POST':
form = my_model_form(request.POST, instance = instance)
if form.is_valid():
# Field1 and field2 is already in the form (its the input)
# Do some back-end operations to get values for the remaining fields
df = some_util_function()
# &downarrow; the instance of the form
form.instance.field3 = df['field3']
form.instance.field4 = df['field4']
form.instance.field5 = df['field5']
form.save()
return redirect("my_html")
else:
form = my_model_form()
context = {
'form': form
}
return render(request, 'discounttracker/my_html.html', context=context)

local variable 'context' referenced before assignment

I need get data from my form and treat them
def parsurl(request):
if request.method == 'POST':
form = DomainForm(request.POST)
context = { 'form': form, }
if form.is_valid():
r = form.cleaned_data.get('url_text')
masall =parser_d(r)
for mas1 in masall:
try:
Events.objects.create(events_title=mas1[1], events_text = mas1[2],events_img = mas1[0], events_is_pars=1, events_seourl = "132")
except:
print ("lololo")
else:
form = DomainForm()
return render_to_response(request, 'form.html', context)
Exception Value:
local variable 'context' referenced before assignment
You have defined context in the if request.method == 'POST' branch, but not in the else branch. Therefore you get an error for GET requests.
You could fix it by moving the line outside of the if statement as follows:
if request.method == 'POST':
...
else:
...
context = {'form': form}

Django didn't return an HttpResponse object

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