Sunday, March 20, 2016

Re: Forms in Django

Stanislav,

If you have any more questions, feel free to post them here.

BTW, one thing I forgot to mention about the flexibility of
the ORM is that you can have it access multiple databases
from the same app, by setting DATABASE_ROUTERS to refer
to a class that tells it things like which DB to use for reading
and for writing each model.

Also, I've had very good luck using the ORM to migrate from
one DB server to another.  For example, on my current project
we're re-writing an old ColdFusion app that used an old
Microsoft SQL Server DB as a new Django app that uses MySQL.

With a one-line command, we were able to create Django
models from all of the MS SQL Server tables:
% manage.py inspectdb

Then with another one-line command, we were able to create
MySQL tables from the models:
% manage.py syncdb

Never had to look at the different DDL of MS SQL Server vs
MySQL, or the native tools of each to export and import DDL.

Since then, we've kept our DEV, TEST, and PROD instances of
the MySQL DB up to date via Django "migrations".

And when we accumulated enough automated regression tests
that it took too long to run the test suite, we changed the
DATABASES setting to use SQLite instead of MySQL when
running tests, by simply adding:
  RUNNING_UNIT_TESTS = 'test' in sys.argv  if RUNNING_UNIT_TESTS:      DATABASES['default'] = {          'ENGINE': 'django.db.backends.sqlite3',    
Again, we never had to look at the different DDL of MySQL vs SQLite, or the native tools of each to export and import DDL. Django did it all for us. Suddenly the entire regression test suite runs in 30 seconds instead of 75 minutes. Really nice!
--Fred
Fred Stluka -- mailto:fred@bristle.com -- http://bristle.com/~fred/ Bristle Software, Inc -- http://bristle.com -- Glad to be of service! Open Source: Without walls and fences, we need no Windows or Gates.
On 3/19/16 8:08 AM, Stanislav Vasko wrote:
Outstanding answer, many thanks! This is exactly what i thought there must be :) Dne sobota 19. března 2016 2:43:31 UTC+1 Fred Stluka napsal(a):
Stanislav (aka Stanley?), As my company motto says:  "Glad to be of service!". I'm very impressed with Django.  It's a mature product that does a good job of:     "Making simple things easy, and complex things possible" It has good simple default behaviors, but also hooks that you can use to drill down to more detail when necessary. For example, in my Django templates, I sometimes use: {{form}} but sometimes have to resort to: {{ form.first_name }} {{ form.last_name }} {{ form.phone }} and occasionally even: {{ form.first_name.value }} {{ form.first_name.label }} {{ form.first_name.errors }} {{ form.last_name.value }} {{ form.last_name.label }} {{ form.last_name.errors }} {{ form.phone.value }} {{ form.phone.label }} {{ form.phone.errors }} Similarly, in my Django ModelForms, I sometimes use: class PersonModelForm(forms.ModelForm):     class Meta:         model=Person but sometimes have to resort to: class PersonModelForm(forms.ModelForm):     class Meta:         model=Person         fields = ['first_name', 'last_name', 'phone',] and occasionally even: class PersonModelForm(forms.ModelForm):     class Meta:         model=Person         exclude = ['middle_name',] or take over a field explicitly as: phone = forms.CharField(     required   = True,     max_length = 50,     label      = u'',     widget = forms.TextInput(         attrs={             'class'       : 'form-control',             'id'          : 'my_custom_HTML_id',             'placeholder' : 'Phone',         }     ), ) or even give up on doing it all declaratively and do something more dynamic in the __init__() of the Form, as: def set_placeholders_from_labels(form):     for field in form.fields.itervalues():         field.widget.attrs['placeholder'] = field.label class PersonForm(forms.Form):     def __init__(self, *args, **kwargs):         super(Donate2Form, self).__init__(*args, **kwargs)         set_placeholders_from_labels(self)         self.fields['amount'].widget.attrs['placeholder'] = ""         if some_special_reason():             self.fields['amount'].initial = "100"         keep_enabled = ['first_name','last_name']         if some_mode_where_we_need_some_fields_disabled():             for field in self.fields:                 if field not in keep_enabled:                     self.fields[field].widget.attrs['disabled'] = True And with validation of user-entered data, I can declare many validation rules on the declarations of the fields, and can do validation programmatically in the clean_field_name() methods and the overall clean() method.  Or can even use the clean() method of the Model instead of the clean() method of the form. The ORM has similar hooks.  I can use it simply, to get() and save() models from and to the DB.  Or can do fancier queries. Or can drop down into raw SQL if necessary. And I can use middleware to inject all sorts of useful functionality into the HTTP request/response cycle, to change or add to the default behavior, add caching of DB data, Django templates, and fully assembled Django pages, etc. And I can hook into Django "signals" for more sophisticated needs. Very powerful! And I've found the community to be extraordinarily friendly and helpful also. Enjoy!
--Fred
Fred Stluka -- mailt...@bristle.com -- http://bristle.com/~fred/ Bristle Software, Inc -- http://bristle.com -- Glad to be of service! Open Source: Without walls and fences, we need no Windows or Gates.
On 3/18/16 3:54 PM, Stanislav Vasko wrote:
This is exactly what i was looking for, many thanks! Now i can render form i need and like. Now i will test and i hope it will be same easy to write data back to db. Many thanks, Stanley Dne pátek 18. března 2016 20:50:37 UTC+1 Fred Stluka napsal(a):
Stanislav, Try these: {{ form.title.value }} {{ form.title.label }} {{ form.title.errors }} etc.
--Fred
Fred Stluka -- mailt...@bristle.com -- http://bristle.com/~fred/ Bristle Software, Inc -- http://bristle.com -- Glad to be of service! Open Source: Without walls and fences, we need no Windows or Gates.
On 3/18/16 2:55 PM, Stanislav Vasko wrote:
This is exactly what im trying. But if i enter {{ form.title }} i get not the data to use in form, but whole: <input id="id_title" maxlength="200" name="title" value="Osobní schůzka, detailní probrání všech prací a podkladů z Topinfo" type="text"> But as i study doc, there is no simple way like Django is providing in other part. So, maybe Fred's way is a good one (but quite strange) and still dont know how i will make Fieldsets and other stuff (i need to work with data and some the result). Maybe there is some better Django Form plugin, but i prefer not to use anything outside Django, because noone knows how it will work with new Django versions and how buggy it can be. As beginner i'm glad for solving own bugs not fighting others too :) You can also do a custom template. So instead of letting Django render the form, you code the html yourself.
This is, instead of:
{{ form.as_p }}
do something like:
<form class="form" action="" method="post">{% csrf_token %}
<div class="col-md-6 col-sm-6 col-xs-12 form-group has-feedback">
    <input name="phone" class="form-control" id="id_phone" placeholder="Phone" type="text">
    <span class="fa fa-phone form-control-feedback right" aria-hidden="true"></span>
</div>
...
</form>
-- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com. To post to this group, send email to django...@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/bb89aebe-5c3a-41dd-8f58-00acb8d78289%40googlegroups.com. For more options, visit https://groups.google.com/d/optout.
-- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com. To post to this group, send email to django...@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/2da88381-e6f0-4e16-8848-c5af5dc87374%40googlegroups.com. For more options, visit https://groups.google.com/d/optout.
-- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/8774a303-b754-4125-9f1e-bf30ccf99a9c%40googlegroups.com. For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment