Getting checkbox value in controller - django

I have a template that creates a text entry field and a checkbox. When the checkbox is unchecked, the text field is disabled and cleared, when it's checked, it's enabled, and the user may or may not have typed in it. In my controller I need to distinguish between the 2
cases when the checkbox is unchecked, and the checkbox is checked but the text field is blank. I can get the value of the text field, but not of the checkbox. Is there some way to do this? I've googled this, and I see it's been asked a few times here, but noneof the solutions seem to work for me.

request.POST.get('my_checkbox_field')
P.S. In Django, they're called "views" not controllers.
UPDATE (based on comment)
I'm taking "controller" to mean "view" since Django doesn't have a concept of controllers and they're closest to views. If that's not the case, by all means correct me. Given that, all function-based views at the very least require a request parameter. If you're using class-based views, then request is simply stored on the view object, so you just need to modify it to self.request. I suggest you take some more time to thoroughly read the docs, as this is pretty much bare minimal understanding stuff that is well documented.

Are you looking for this?
def myview(request):
form = MyForm()
if request.method == 'POST':
form = MyForm(request.POST)
if form.is_valid():
checkbox = request.POST.get('my_checkbox', False) # will be True if checked
if checkbox:
# check textfield content
else:
# do something else
return render_to_response(template, kwvars, context_instance=RequestContext(request))

Related

Django - Transfer data from view to form

I am struggling with the update of database information with the forms, and simply passing information between views. I could really use some advice because I am fairly new to Django.
The flow goes like this:
1. First form; I transfer the article price and title to the view "event"
2. The view "event" handles title and price and ask for confirmation in the html form
3. Once confirmed, it directs that information to the view "transact_test", I want this view to handle the update of the database via a new form that is build with the Article model. But it provides the error message : "didn't return an HttpResponse object. It returned None instead."
To fix your error: In transact_test you are just calling render in the request.method == 'POST' block:
render(request, ...)
You need to return render:
return render(request, ...)
You should really take a look at some additional django tutorials you are making this harder than you need to. You should almost never manually render a form when using django. And as Tariq said, please don't use images.

Repeating a large form in a form wizard

I'm trying to create a form wizard which starts with a repeatable form for adding multiple trainees.
The user can add as many trainees as they like, with each of the "Add Trainee" forms being quite a long form asking for lots of details.
Once the user has added all of their trainees, there are 3 or 4 more forms before the wizard is complete.
What is the best way to do this?
I was wondering whether adding the trainees to the session would be the simplest idea but this might break some of the wizard functionality, like being able to go back etc.
And because the "Add Trainee" form is so long, it doesn't make sense to use a formset on the first form wizard page, I don't think.
Any ideas?
You might be able to get away with modifying the post method with something like this.
if form.is_valid():
# if the form is valid, store the cleaned data and files.
self.storage.set_step_data(self.steps.current,
self.process_step(form))
self.storage.set_step_files(self.steps.current,
self.process_step_files(form))
# check if the current step is the last step
if self.steps.current == self.steps.last:
# no more steps, render done view
return self.render_done(form, **kwargs)
# check if trainee form is current form
elif self.steps.current == "trainee_form":
mentor = User.objects.get(id=self.request.user.id)
Trainee.objects.create(
mentor=mentor,
data1=self.request.POST["trainee_form-data1"]
data2=self.request.POST["trainee_form-data2"]
data3=self.request.POST["trainee_form-data3"]
)
if self.request.POST["trainee_form-add_new"] == True:
self.render.go_to_step["trainee_form"]
else:
return self.render_next_step(form)
else:
# proceed to the next step
return self.render_next_step(form)
return self.render(form)
You'll have to fiddle with it, but hopefully it sparks an idea.

Display alert after form submitted Django

I would like to display an alert box after a form has been submitted.
The box would be hidden when a user first visits the page and will display "new category created" or "category already exists" upon submission.
I think I know would I can do this in the template but I'm not sure how to pass the variable into the template on the redirect.
Below is the view. Any thoughts how I can accomplish this?
I appreciate the feedback.
#login_required
#locationed
def manage_cat_subcat(request, location):
form = AddCategory()
if request.method == 'POST':
form = AddCategory(request.POST)
if form.is_valid():
submitted_cat_name = form.cleaned_data['category_name']
_, was_created = Category.objects.get_or_create(name=submitted_cat_name)
return HttpResponseRedirect(reverse('manage_cat_subcat', args=(location.slug,)))
return render(request, 'inventory/manage_cat_subcat.html', {'location': location, 'form': form})
You don't have to use any hidden data, just use this:
https://docs.djangoproject.com/en/dev/ref/contrib/messages/#using-messages-in-views-and-templates
It looks like you're talking about rendering a dialog based upon a user submitting certain information. If so, I strongly recommend using JQuery to pull the value of the category field once the field loses focus, then pass that category information right away via an AJAX call to a dedicated method in your views file. Depending on the response, you'll show the appropriate dialog. So it would be something like this in your views.py:
#render_json
def ajax_category_check(request){
if request.method == 'POST' and 'category_name' in request.POST:
#insert your code that checks new or existing categories
#if the category exists...
return {'exists': True}
return {'exists': False}
}
One advantage of AJAX is that it makes the user experience a lot smoother by removing the burden of having them deal with form submission/browser page refreshing.
On the other hand, if you're talking about simply showing an alert dialog before the form is even submitted, intercept the form submission and show the dialog using JQuery:
$('form').click(function(event){
$('#dialog').show();
/* after a delay or after dialog confirmation, etc... */
$('form').submit();
});

Django: Form in base template

Hi Stackoverflow people,
In my Django project I created a form to register users. This forms can be called through a specific url -> view method. Once the user has filled in the form, presses submit, the same view method will be called and if form.is_valid() is true, then ... simply a standard form, nothing special.
Now, I would like to integrate this little form on every page, and therefore I would like to add it to the base template. I have read that I could populate the form variable through a context_processor, but could I define the process after the submission of the form?
I have created the context_processor.py (as below), added the context_processor to the TEMPLATE_CONTEXT_PROCESSOR dir in the settings (as described here):
from app.forms import Form
def registration_form(request):
return {
registration_form : Form()
}
First of all, the form variable won't be displayed.
And secondly, how do I manipulate the form submission?
I think I misunderstanding the context_processor of Django and would be more than happy about comments on the overall process.
Thank you!
how are you trying to access to form in your template? you probably don't want to use a function name as your dictionary key, maybe you want
return {
'registration_form': Form(),
}
not sure what you mean by manipulate the form submission, but i guess you'd need all the form processing logic in your context processor
if request.POST:
form = Form(request.POST)
# validate etc
instead of creating context processor, create template tag for the purpose and place the tag in base.html
for form submission and displaying errors use ajax, and front-end validations.

How to write good form validation in Django?

I've seen Django's samples and I can see they have decent error handling. However I want to see if there is yet a better approach, a general pattern to handle form validation errors in Django. This is the sample I found here:
def contact(request):
if request.method == 'POST': # If the form has been submitted...
form = ContactForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
# Process the data in form.cleaned_data
# ...
return HttpResponseRedirect('/thanks/') # Redirect after POST
else:
form = ContactForm() # An unbound form
return render_to_response('contact.html', {
'form': form,
})
In particular, I was wondering:
How can the view in "/thanks/" be sure that the form was validated? Are there any common ways to pass the successful validation of the form to the next view? Or do I need to do something manually such as setting a flag in request's session?
How can one write this code in a way that when form is NOT valid and the page is shown with errors upon submission, if user refreshes the browser it wouldn't ask the user if they want to POST data again?
EDIT: With regards to #1 I am referring to cases like user manually entering the '/thanks/' url or going back and forth through history pages and accidentally openning it without any form being validated. (Do we still show the "thanks" page? or we need to somehow re-validate why we are in thanks view).
The view can be sure that the form is validated because it will only be called if the form is valid...
If the page is generated through a post request the browser will always ask you that when hitting refresh... I guess the only way to avoid this would be redirecting to another page!
How can the view in "/thanks/" be sure that the form was validated?
form.is_valid() should thoroughly check any field or - if necessary - any combination, cornercase, etc. That's basically it. The views knows, the form was valid if it renders. There is no need to include redundant information in the session.
How can one write this code in a way that when form is NOT valid and the page is shown with errors upon submission, if user refreshes the browser it wouldn't ask the user if they want to POST data again?
I am not sure what the point would be. The form contains errors and the user may correct them or leave. To render a page that would not ask for form resubmission, one could use a redirect, just as in the valid case. The error markup would have to be done manually in that case.