Are there any real reason to use builtin forms in django?
One of them as I understand is validation. Ok. And maybe some convinience (but not for me).
Anything else?
Is there any acceleration in site work with forms?
From Django documentation -
While it is possible to process form submissions just using Django’s
HttpRequest class, using the form library takes care of a number of
common form-related tasks. Using it, you can:
Display an HTML form with automatically generated form widgets.
Check submitted data against a set of validation rules.
Redisplay a form in the case of validation errors.
Convert submitted form data to the relevant Python data types.
Also django forms provide some level of security by enforcing CSRF.
Some of the cool things you can do with django forms
I agree that in some circumstances, the temptation to avoid the use of Django form is very strong.
If I need just one field with no validation nor style, why should I define a django-form?
HTML:
<form method='POST' action='url_to_my_view'>
Type something: <input type='text' name='any_value'/>
</form>
Django:
<form method='POST' action='url_to_my_view'>
{{ form }}
</form>
with the overhead of defining the form and including it in the view.
But I still use Django-forms: experience tells me that software shortcuts always lead to problems...
The more built-in forms, the less work for developers. You are free to implement them from 0 but it is always faster to use something that is already done and tested.
Anyway, you have something in the middle: inherit from built-in forms and customize them.
Related
Working on an app, I initially started developing the UI via QT (PySide2) but I paused it to work on a full "online version" via Django.
The fact is that I'm learning/discovering the framework and how it works step after step.
For all HTML I'm building those on Bootstrap Studio which help me to save A LOT of time and of course make things totally easier for me.
My current problem is that I just discovered how not simply inputs/forms work in Django (My own opinion !). My app works with several bootstrap modals in order to Add/Edit "element" which are the kind of instances of my app and which will be write/read/edit in the database.
The problem here is I already created all HTML pages and related bootstrap-modals and I can't find any way on the internet to link my existing bootstrap-modals to Django forms.
As far as I understood Django forms "caricaturaly" works like this: Django generates a form that you have to dynamically integrate into your HTML.
The fact is it doesn't really arrange me because :
I already have my bootstrap-modals with their inputs looking how I want
I don't really want a bad looking forms as Django generates
I have other elements in the form which are not related to a form (progress bar)
Any other things I have no idea about since I am a beginner in Web!
Therefore, my main question here would be: Is there any simple/accessible way to get the inputs as it would be via QT, by this I mean :
Opening the modal
Filling Input_1, Input_2, Input_3
Any way in Django files to get those inputs and then saves those in DB (one by one)
My apologies if really looks dumb here but I am really new to Django/Web, I know CSS/HTML syntax, I have NO knowledge in JavaScript and I would say that my Python level is Intermediate (enough for all my back-end uses).
Thank you in advance for your help!
A simple example of using a form for validation/processing but not html generation.
Assume we have this existing form
<form action="/some-url" method="POST">
<input id="foo" name="foo" type="text"/>
<input id="bar" name="bar" type="text"/>
<input id="baz" name="baz" type="text"/>
</form>
you can represent it with this Django form:
class MyForm(forms.Form):
# Field names should match the 'name' attributes in the html inputs
foo = forms.CharField()
bar = forms.CharField()
baz = forms.CharField()
And use it in view like this
def my_view(request):
if request.method == 'POST':
form = MyForm(request.POST)
if form.is_valid():
# Do stuff
return HttpRedirectResponse('/success')
# No need to pass the a form to the template, because we aren't
# using it to generate html.
return render(request, 'view.html', {})
If you want to use a field from the html form separately, without using a Django form at all, access it directly:
some_val = request.POST['some_val']
(beware of false booleans and disabled fields, which will not be present in request.POST).
I am new to Django and tried making a view that holds a list of forms and handles them. I am familiar with the FormView provided by django's generic views however it only holds one form in it.
The idea is that the main form I have is split into a few forms, and then the "mini-forms" are held in a list ("forms").
Since I'm splitting the form into parts and saving a list of forms (for reasons like re-usability and such), the template looks something like this (which does the trick):
...
<form ...>
{% for form in forms %}
{{ form.as_p }}
{% endfor %}
<input type="submit"...>
</form>
...
I have been messing around with the view that should handle the forms, validate them and will get the data from them. Since I feel like Im making it more complicated than it should really be, I'd like to ask you to give an example of a simple view for that, that Ill develop further (get
This may be more a comment but I don't have quite enough rep to respond as a comment so I'm putting this in an answer:
If your primary concern is reusability have you considered creating Mixins instead of making a list of forms?
an example of this could be:
from django import forms
class NameFormMixin(object):
your_name = forms.CharField(label='Your name')
class EmailFormMixin(object):
email = forms.EmailField(label='Your Email')
class NameEmailForm(forms.Form,
NameFormMixin,
EmailFormMixin):
pass
you could include your validation functions in the mixins and have general django form functions in the main form class.
In templates you can write forms in several ways: either by an already created Django form or by a plain html form. Both of them are okay, and can be used, so I am interested in case of using each form. I've used ModelForm several times and it's a really nice shortcut, also I am reading a Django book and Django forms are introduced as a good way of validation, even if you won't use them in your templates. But also many tutorials show html forms where a django froms are expected (at least for me). An example in a search form. All of the tutorials I've seen use plain html form, capture a query and return a queryset. Why wouldn't they write a separate form and use it as {{ SearchForm }}?
Personally, I never use {{ form.field }} syntax in my templates. I always write HTML for my forms. Because it is easy to assign classes, ids and other data attributes to form inputs in HTML rather than doing the same in forms.py
When you need to assign classes and ids to form inputs, you will need to do something like this:
myfield = forms.CharField(
widget=forms.TextArea(
attrs={'class': 'some-class',
'id': 'SomeId',
'rows': '10',
'style': 'margin-top: 10px;',
}
)
)
Frankly, it sucks. Now compare the above code with this:
<textarea name="myfield" rows="10" class="some-class" id="SomeId" style="margin-top: 10px;"></textarea>
And now your Django code can get a little shorter, thereby cleaner:
myfield = forms.CharField()
The HTML syntax is far better than corresponding Python syntax. It feels more natural. Also, if you've got a designer working with you on a project who doesn't know Python, this way you both won't interfere with each other's development process.
I have blog comment forms in Django and I would like to know the following:
Should I add CSRF to the forms?
If I want to use the simple "render_comment_form" method, how do I add it?
If I can't add it like that, what is the best practice for doing it?
Each tutorial or discussion on the subject seems to have a different approach, and I am not certain I understand how it all works.
My answer assumes that you are using Django 1.2:
Yes! You should protect all your data that is sent by POST requests to the server against CSRF attacks.
You don't need to add the token yourself. This is already done by django. Have a look at the default template that is used by the render_comment_form tag and you will see, that the csrf_token is already included. You can overwrite this template in your project and including the CSRF token into it is as easy as writing {% csrf_token %} into the form.
There is a way to protect your forms even if you don't set the tokens in the templates. Have a look at django's documentation about that topic. But this method is marked as a legacy method so it's not recommended to use that - it's only provided for backwards compatibility with versions of Django earlier than 1.2.
I just started to use django. I came across forms and I need to know which one is the better way to validate a forms. Would it be using django forms or should we use javascript or some client side scripting language to do it?
You should ALWAYS validate your form on the server side, client side validation is but a convenience for the user only.
That being said, Django forms has a variable form.errors which shows if certain form fields were incorrect.
{{ form.name_of_field.errors }} can give you each individual error of each field that's incorrectly filled out. See more here:
http://docs.djangoproject.com/en/dev/topics/forms/
There's a pluggable Django app (django-ajax-forms) that helps validate forms on the client side through JavaScript. But as AlbertoPL says, use client side validation only as a usability measure (e.g. telling a user that his desired username is already taken without reloading the registration page). There are all kind of ways to sidestep client side validation, in most cases as simple as deactivating JavaScript.
Generally speaking: presume all data coming from the outside as faulty until validated.
Just came accross django-floppyforms, which seems to do clientside validation by default. They use HTML5 which supports clientside validation by default. Not sure if they also use javascript though if the browser doesn't support HTML5. Haven't tried it myself yet.
Link to django-floppyforms: Documentation and Github
If you are using bootstrap then you can simply add required attribute in forms field. For example if there is programe field then you can validate it like:
In forms.py:
programme = forms.ChoiceField(course_choices,required=True, widget=forms.Select(attrs={'required':'required'}))
Note: It requires to link to bootstrap files in your .html page of that form.
You will need to do this is JS. This app integrates forms with parsley.js to tag the forms with correct data-* attributes automatically.