Django view doesnt seems to have any request object - python

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

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.

Django show error in form that comes from another function

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.

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: Handling form data after a redirect

I have a Django app with two views (actually more but I'm simplifying). The first view shows a page with details regarding an object and has a form which can be submitted. The second view is called buy the POST request on submitting the form and then redirects back to the first view:
views.py:
def main_view(request):
context = {}
# other view code here
context['form'] = Form()
return render(request, 'mypage.html', context)
def form_view(request):
form_data = Form(request.POST)
if form_data.is_valid():
# process form here
else:
# add an informative message
messages.add_message(request, messages.INFO, "Error message here")
return redirect('url_of_main_view')
The issue I have here is that I want to pass the form data back to the main view, both to prevent the need to fill in the whole form again, and to allow the validation errors to be displayed.
I would normally do this by simply processing the form within one single view, such as:
def view(request):
context = {}
# other view code here
context['form'] = Form()
if request.method == 'POST':
form_data = Form(request.POST)
if form_data.is_valid():
# process form data
else:
# handle messages
context['form'] = form_data
return render(request, 'mypage.html', context)
However, this (in my case at least) would result in a large view as I have a number of different forms that can be submitted from this page. I also like to redirect after a form post to avoid the data being re-submitted if the user refreshes the page.
My questions:
Is this (the first example) indeed a sensible way of structuring the code for handling forms? Is the second example a more sensible way of doing this, or is there a better idea? Perhaps I should perform form validation within the main view then call a separate method to process the form data?
If I were to use the first example, with a separate view to handle a form post, what is the best way to go about handling instances in which the form fails validation and should be passed back to the main view? Should I be using sessions for this, or is there a more efficient/cleaner way of doing this?
Thanks!
Alex

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