Django show error in form that comes from another function - python

I am trying to post a ModelForm, but after the is_valid() function, I run another validation coming from another function.
What I want to do is, if the result of the other function is false, the form should raise an error, above the form as in the case "your password cannot be the same".
Since the function runs during the process, I cannot use a clean method in model.
Thanks in advance!
function
def somefunction():
.
.
print ("NOT WORKING")
return False
views.py
def index(request):
form = SomeForm(request.POST)
if request.method == "POST":
if form.is_valid():
if somefunction() == True:
form.save()
return HttpResponseRedirect("/contact/")
else:
form
else:
form
return render(request, "home.html", {'form': form})

You can use add_error method to add error to form manually like this.
form.add_error('<FIELD_NAME>)', 'your password cannot be the same')
But I suggest you to override clean method of form instead.

Related

Obtaining data from the form with GET data. Django

How can I get data from the form using the GET method?
For example, I have this form:
class LoansSearchForm(forms.Form):
balance = forms.IntegerField(label='', required=False)
In my view display in the form template this way:
def search_results(request):
form = LoansSearchForm(request.GET)
cd = form.cleaned_data
word = cd['balance']
context = {'form': form,
'test': word,}
return render(request, 'search_results.html', context)
But i still a error:
'LoansSearchForm' object has no attribute 'cleaned_data'
When trying to get them this way:
word = form['balance']
I receive a field with completed data. How to get the data from my the form correctly?
Is my form written correctly? Should I use something like that?
(sorry if my question is trivial, but I found very little information about GET forms)
if request.method == 'GET':
form = LoansSearchForm(request.GET)
if form.is_valid():
print('Hello World')
else:
form = LoansSearchForm()
Recommended: run form.is_valid() and then you do form.cleaned_data
def search_results(request):
form = LoansSearchForm(request.GET)
if form.is_valid():
cd = form.cleaned_data
word = cd['balance']
else:
word = None
context = {'form': form,
'test': word,}
return render(request, 'search_results.html', context)
Forms only get a cleaned_data attribute when is_valid() has been called, and you haven't called it anywhere.
more on cleaned data - documentation
def search_results(request):
form = LoansSearchForm(request.GET)
cd = form.cleaned_data # here <------
word = cd['balance']
context = {'form': form,
'test': word,}
return render(request, 'search_results.html', context)
The problem with your code is that forms are not filled on initialization but when you call form.is_valid, if the form is indeed valid, then it populates cleaned_data
You can read more about the related documentation.
I used name=form.data['field_name'], think it answers your answer of obtaining form values on submit.

Why calling method inside views.py after successful submission of forms doesn't clear the form?

Views.py
def form_name_view(request):
form = FormName()
if request.method == "POST":
form = FormName(request.POST)
if form.is_valid():
form.save(commit=True)
return HttpResponseRedirect('/') # return index(request)
else:
print('INVALID FORM INPUTS')
return render(request, 'first_app/form_page.html', {'form': form})
When I use HttpResponseRedirect to get back to my index page, then everything works correct, but the concern is if I use calling index method instead of HttpResponseRedirect then the behavior is a little bit insane:
After reaching index page if I hit refresh then alert appears says:
The page that you're looking for used information that you entered.
Returning to that page might cause any action you took to be
repeated. Do you want to continue?
If i want to get back to the same form page, by calling that same method again like
return form_name_view(request)
The new form is already filled with previous inserted data, with the message on the form
Topic with this Topic name already exists.
The question is what is the reason, calling method results like this?
def form_name_view(request):
if request.method == "POST":
form = FormName(request.POST)
if form.is_valid():
form.save(commit=True)
return HttpResponseRedirect('/') # return index(request)
else:
print('INVALID FORM INPUTS')
else:
form = FormName()
return render(request, 'first_app/form_page.html', {'form': form})
use this

Django view doesnt seems to have any request object

I am trying to get request.user but even printing request doesn't works.But nothing is printing
view.py
def flower_add(request):
print request
print request.method
if request.method == 'POST':
print 'xxxx'
form = FlowerAddForm(request.POST)
if form.is_valid():
print "form is is_valid"
form.save()
context= {'form':FlowerAddForm()}
return render(request, 'farmer/flower_add.html',context)
else:
form = FlowerAddForm()
return render(request, 'farmer/flower_add.html', {
'form': form,
})
Your view here may be working but you likely won't get any output to the console using print in the manner you are using it.
Try calling print() as a function with request explicitly passed.
Also, print() is ideal for string objects (as well as int, etc) but no so much for more complex types such as dictionaries, lists and other structured objects.
Try using pprint() instead:
pprint(request)
print(request.method)
https://docs.python.org/2/library/pprint.html

simple django code snippet from file upload

sorry for dumb question.
def upload_file(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
handle_uploaded_file(request.FILES['file'])
return HttpResponseRedirect('/success/url/')
else:
form = UploadFileForm()
return render_to_response('upload.html', {'form': form})
what happens really in the background when i bind the request to the Form?
It creates an empty form to be passed to the template upload.html since the previous form in upload.html did not pass the validation. When a form has some error, Validation Error exception is raised, then the form is invalid, or when the view is called and request does not include the method POST therefor you must render it again.

Django: construct form without validating fields?

I have a form MyForm which I update using ajax as the user fills it out. I have a view method which updates the form by constructing a MyForm from request.POST and feeding it back.
def update_form(request):
if request.method == 'POST':
dict = {}
dict['form'] = MyForm(request.POST).as_p()
return HttpResponse(json.dumps(dict), mimetype='application/javascript')
return HttpResponseBadRequest()
However, this invokes the cleaning/validation routines, and I don't want to show error messages to the user until they've actually actively clicked "submit".
So the question is: how can I construct a django.forms.Form from existing data without invoking validation?
Validation never invokes until you call form.is_valid().
But as i am guessing, you want your form filled with data user types in, until user clicks submit.
def update_form(request):
if request.method == 'POST':
if not request.POST.get('submit'):
dict = {}
dict['form'] = MyForm(initial = dict(request.POST.items())).as_p()
return HttpResponse(json.dumps(dict), mimetype='application/javascript')
else:
form = MyForm(request.POST)
if form.is_valid():
# Your Final Stuff
pass
return HttpResponseBadRequest()
Happy Coding.

Categories

Resources