Trouble posting un-checked checkbox value in django - python

I am finding trouble in posting the state of a checkbox in a Django form (Django v1.2).
Here's the field in my model:
subscribe = models.BooleanField(default=False, verbose_name="Subscribe")
In the relevant template file:
{{ form.subscribe }}
This renders the checkbox as un-checked initially. But when I post the form (without touching anything else), django sends u'subscribe': [u'on'] in request.POST. That is, the response always contains u'subscribe': [u'on'] irrespective of whether the checkbox is checked or not.
When the checkbox is not checked, the <input> tag in template is rendered as
<input type="checkbox" name="subscribe" id="id_subscribe" />
And, when the checkbox is checked, it is rendered as
<input type="checkbox" name="subscribe" id="id_subscribe" checked="checked" />
Am I missing anything here?

Your browser is what posts the value as 'on'. This is normal behavior for checkbox inputs without value="blah" attribute set. If it is always posting as 'on' even when the checkbox isn't checked then perhaps there is something on the browser side that is setting this.

Related

Flask routing does not give desired results, URL not getting appended for some instance

I am building a web-app using flask where I am trying to route some URLs
I have three routes with me
a) "/"
b) "/teacher"
c) "/student"
The routing works fine for "/" and"/student" The URL gets appended after clicking the submit button for student and"/student" gets appended in URL but on clicking the button associated with "/teacher" the URL doesn't gets appended and "/" page keeps on loading up.
Please help me out here and tell me what wrong I am doing
My Python code:
#app.route('/', methods=['GET', 'POST'])
def select():
return render_template("select.html")
#app.route('/teacher', methods=['GET', 'POST'])
def index():
return render_template("index_teacher.html", title="Faculty login")
#app.route('/student', methods=['GET', 'POST'])
def index1():
return render_template("index_student.html", title="Student login")
Part of my html code from select.html:
<form action="/teacher" method = "post">
<input type="submit" class="submit" value="Login as Teacher">
</form>
<br>
<form action="/student" method="post">
<input type="submit" class ="submit" value="Login as Student">
</form>
One more thing about the code, when I add a text box above the first submit button, both the button starts working and give desired results.
Thanks in advance!
I think you have just a little typo in the html. The input tag of teacher didn't close >.
<form action="/teacher" method = "post">
<input type="submit" class="submit" value="Login as Teacher">
</form>
<br>
<form action="/student" method="post">
<input type="submit" class ="submit" value="Login as Student">
</form>
EDIT:
In the case that the question was copied incorrectly, I don't know what should be wrong with your code. For me your sample code works just fine. So from my experience with flask and html forms the most common errors I made are the following, maybe it's one of them (the list may serve other too, so I will also add points that do not make sense for your case):
method name of two routes collide (e.g. both '/' and '/teacher' are assigned to function index, but that should give an error when starting the server, so not really possible)
an html tag is not closed properly, so the form in question is not parsed as a valid form (that was my guess with above answer, also makes sense with the text box, which may close the corrupt tag => in html an open tag is closed by the first following closing tag)
typo in the form action attribute (check the network tab in your browsers developer tools, maybe you get an error response to something like "taecher", which results in a redirect to "/", again not really plausible with the fact that it suddenly works when you add the text box)
typo in the route or the returned template (again not plausible with explained behavior with the added text box)
That's all I can think of at the moment. I hope it helps with the search. if you could add more of your html code, maybe I find something suspicious.

Redirect back to previous page after login in django-allauth

There is a button in blog detail view that asks user to login to comment, but after login user is redirected to home page because in settings.py I declared:
LOGIN_REDIRECT_URL = "projects:home"
I searched and I found this could be a solution:
Please login to reply
but this even didn't work.
Thank You
You are half-way there: When you add ?next={{request.path}} to your a tag, you are creating a 'next' variable and assigning the current path to it. But that alone isn't enough for your desired result; you still need to actually use that variable in your login form.
You haven't shown us your login template, but I assume it's a basic form. Add a hidden button to the login form, and have it use the 'next' variable that was captured in your a tag. Put the following code inside your login form tag, after everything else, but before closing the the form:
<input type="hidden" name="next" value="{{ request.GET.next }}" />
When a user submits the Login form, the template will use the value stored in request.GET.next, which was captured from your a tag.

Two different submit buttons in same form in Django

I have an UpdateView in Django.
I have just a normal submit button. When the object is updated correctly it redirects to an object list via success_url.
Can I make two different submit buttons: One button which submits and redirects to objects list page (ListView) and another button which submits and redirects to the object detail page (DetailView)?
I don't know how to do this in a smart way.
Since you're submitting to the same place, and only want to change the redirect destination after save, this is simple. Submit buttons are just like any other input controls in that they have a name and a value, and you receive these in the POST data. So, in your template you can have:
<input type="submit" name="list" value="Submit and go to list">
<input type="submit" name="detail" value="Submit and go to detail">
and in your view:
if form.is_valid():
form.save()
if 'list' in request.POST:
return redirect('list_url')
else:
return redirect('detail_url')

Django BooleanField always checked even when value is false

I have a BooleanField in a standard Django Form defined as:
my_boolean_field = BooleanField(initial=True)
when I render my form with initial data, and my_boolean_field is set to an initial value of False, when the form renders it is still checked despite the fact that the value is false as the html shows:
<p><label for="id_2">my_boolean_field</label>:
<input checked="checked"
type="checkbox"
name="2"
value="False"
id="id_2" />
</p>
Has anyone else experienced this, or knows how to fix it so that when the initial data/input value is false then the checkbox is not checked?
UPDATE: Even if I remove the initial=True argument from the BooleanField the same thing happens.
Firstly, you can't have required=False on a BooleanField, use NullBooleanField instead:
https://docs.djangoproject.com/en/dev/ref/models/fields/#booleanfield
https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.NullBooleanField
let me know what the HTML output of the new widget is once you've done this?
EDIT
I assumed that this is a ModelForm. Is this a regular django.forms.Form?
EDIT 2
My test form:
from django import forms
class MyForm(forms.Form) :
"""The test form"""
my_boolean_field = forms.BooleanField(initial=True)
My template:
<div>
{{ form.my_boolean_field.label_tag }}
{{ form.my_boolean_field }}
{{ form.my_boolean_field.errors }}
</div>
This is what I get for output when I view page source. EDITED
<div>
<label for="id_my_boolean_field">My boolean field</label>
<input type="checkbox" name="my_boolean_field" id="id_my_boolean_field" />
</div>
My View NEW
form = MyForm(initial={'my_boolean_field':False})
What you are showing and what I'm seeing aren't matching up. paste your full form, view and template please?
EDIT 3
I only see output like this:
<div>
<label for="id_my_boolean_field">My boolean field</label>
<input checked="checked" type="checkbox" name="my_boolean_field" value="False" id="id_my_boolean_field" />
</div>
when I put False in quotes:
form = FormLogin(initial={'my_boolean_field':"False"})
I'm posting this answer because I had the same problem and Francis's answer didn't help me.
I eventually found the solution was to re-run manage.py syncdb. My fields had previously been IntegerField and I had converted them to BooleanField. BooleanField read the presence of value="0" in the database as being initialized and checked. This is regardless of what your model says. You want to see:
<input checked="checked" id="id_cost_track_destruction" name="cost_track_destruction" type="checkbox">
when you inspect an element. Since this bug shows up in the Django Admin panel, it has nothing to do with your forms.py.
This is purely a model and database issue. Try regenerating your database if you've changed your models.py field types.
For those who are using ModelForms, this is what worked for me:
password_required = forms.CheckboxInput(attrs={'checked' : ''})
This correctly generates the checkbox with it unchecked.

After POST, weird redirect to iana.org follows

I'm using django-voting: https://github.com/brosner/django-voting/tree/master/voting
And after my post, I'm redirected here: http://www.iana.org/domains/example/#c40
<form method="POST" action="/comments/{{ comment.id }}/up/vote/">
{% csrf_token %}
<button type="submit">Thumbs Up!</button>
</form>
The vote is created and I can see it in the admin.
No where in my application do I have this kind of redirect. Nor can I find this line of code in django-voting where it would have this redirect. Has this happened to anyone else, if so how'd you solve this?
I just want to be redirected the same page after the casted the vote. So I tried <input type="hidden" name="next" value="{{ event.get_absolute_url }}" /> thinking that it might override. But this doesn't seem to work. Suggestions?
I'm guessing that somewhere in your logic you redirect to "example.com". example.com is owned by the IANA and redirects to http://www.iana.org/domains/example/.
Also, the "#c40" at the end of the url makes me think that Django is trying to redirect back to some page with a c40 anchor, possibly in order to have the thing you just voted on in view.
Are you using the Sites framework? (Do you have a Sites model in your admin?) If yes, this may be due to having an instance of a Site model with the domain name "example.org" which is the default.
Furthermore, there may be a fixture that reloads 'example.org' into the Sites each time you do something with the database, such as a migration with South, for example.
That redirect happens when you hit one of the example domains, listed in RFC 2606.
There's something somewhere in your code that's pushing to example.com or another one of the example domains.

Categories

Resources