Django Form object, change HTML attribute outside python code/models - python

I'm looking to understand a way to change attribute of my html code generate by the django's template system, especially for Form html code.
So I found some stuff to change class from some models like that
class AuthorForm(ModelForm):
class Meta:
model = Author
fields = ('name', 'title', 'birth_date')
widgets = {
'name': Textarea(attrs={'cols': 80, 'rows': 20}),
}
coming from here.
It's fine and it could works. But actually django, if I understand almost well, use a templates system which can be read by someone else, a front-end developper for a simple example. Now, Boostrap come whith the need to manipulate class attribute to work on the style. When we work on a loop, it's not a problem, but when whe generate the HTML code from a class who inerhit Form and just display it in a template, it will be be quickly harder for someone else to manipulate html balise. For sure they can do that with javascript, it's the solution that I've in mind, but it seem not really nice. There is an alternativ way to do that ?
Thanks for suggestion, I hope I was relatively clear.

Related

When to use a django form and when to use a html one?

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.

CheckboxSelectMultiple not displaying checkboxes with Django-Material

I'm fairly new to Django so please bear with me.
I'm using a ModelForm along with Django-Material (By Viewflow) and it's working really well expect for one thing. It doesn't display checkboxes.
My 'Person' model has a ManyToMany relationship with 'Problem' and I've set the form to show checkboxes as so -
class PersonForm(forms.ModelForm):
class Meta:
model = Person
exclude = ('',)
widgets = {
'problems': forms.CheckboxSelectMultiple(),
}
But it shows up like this
When I remove the Material template the checkboxes show up properly
I'm not really sure if there's a problem with Django-Material or something I may have missed. Help would be really appreciated, thanks!
Actually it was not implemented in time when question was.
Not it works as expected and in addition could be rendered in several columns
http://forms.viewflow.io/demo/hospital/
Alright, so it turned out that they haven't included that functionality in Django-Material yet

How a django form is passed to a html template

I am new in Django framework and trying to understand how it works and what is its structure. I am just curious about how a django form is passed to a html template ? Any help would be appriciated.
I think you are curious in how django converts a python object into HTML, its internal mechanism, so the tutorial might not cover what it is.
I did have the same question before, but if you do look at code in forms.py https://github.com/django/django/blob/master/django/forms/forms.py you will see that internally there are methods which will look at the attributes of the objects that you have declared and generate snipplets of html code which will then be rendered.
Of course I cant tell you exactly how it works, I leave the heavy lifting to django.. Isn't that why we use a modern web framework like django in the first place.
Hope you will find this useful

Use autocomplete light with django-tables2

I'm trying to populate a django table with autocomplete light so that the user can fill in data in the table, which would then be saved (the whole table is in a form tag). I have the table working to display the existing data and I have the autocomplete working in model forms (well, a team member got that part working), but I don't know how to combine the two. The docs are a bit of a mystery to me, but maybe if someone could at least point me in the right direction I'd greatly appreciate it.
I've tried a few random things to combine them, but honestly they were such stabs in the dark that I don't think they're even worth mentioning.
tables.py
class ModifyTable(tables.Table):
name = tables.LinkColumn('app-view', args=[A('pk')], verbose_name='Name')
primary_contact = tables.Column()
secondary_contact = tables.Column()
autocomplete
autocomplete_light.register(Person,
search_fields=['first_name', 'last_name', 'username'],
split_words=True,
autocomplete_js_attributes={'placeholder': 'Find a user',},
)
Django-tables2 provides an API to generate data tables in HTML.
Django-autocomplete-light provides a widget that enables autocompletion inputs.
This widget must be used in a Form. The django Form class will combine your the HTML <form> with models used by django-tables2.
However, a Form must be used by a Formsets to be repeated for every row in the table. Note that you could consider modelformset_factory to generate such a formset.
Use a formset and your work is done here ;)

Return template as string - Django

I'm still not sure this is the correct way to go about this, maybe not, but I'll ask anyway. I'd like to re-write wordpress (justification: because I can) albeit more simply myself in Django and I'm looking to be able to configure elements in different ways on the page. So for example I might have:
Blog models
A site update message model
A latest comments model.
Now, for each page on the site I want the user to be able to choose the order of and any items that go on it. In my thought process, this would work something like:
class Page(models.Model)
Slug = models.CharField(max_length=100)
class PageItem(models.Model)
Page = models.ForeignKey(Page)
ItemType = models.CharField(max_length=100) # tells me which model to display
InstanceNum = models.IntegerField() # tells me which instance of which model...
Then, ideally, my template would loop through all the PageItems in a page which is easy enough to do.
But what if my page item is a site update as opposed to a blog post? Basically, I am thinking I'd like to pull different item types back in different orders and display them using the appropriate templates. Now, I thought one way to do this would be to, in views.py, to loop through all of the objects and call the appropriate view function, return a bit of html as a string and then pipe that into the resultant template.
My question is - is this the best way to go about doing things? If so, how do I do it? If not, which way should I be going? I'm pretty new to Django so I'm still learning what it can and can't do, so please bear with me. I've checked SO for dupes and don't think this has been asked before...
I've also looked at Django-cms to see if that helps, but I couldn't get to grips with it.
Any suggestions?
First, some puzzelement.
InstanceNum = models.IntegerField() # all models have primary keys.
In Django, all model are assigned an integer primary key.
The comment doesn't make sense, since you don't need to add a primary key like this. The PageItem already has a primary key.
Also, please use lower case letters for attributes. Only Use Upper Case for Class Names. Please.
"But what if my page item is a site update as opposed to a blog post? Basically, I am thinking I'd like to
pull different item types back in
different orders and display them
using the appropriate templates"
Different types usually means different models. Rather than a vague "PageItem", you probably want to have "Site Update" and "Blog Post" as separate models.
You can then iterate through these various objects and display them in the template.
You can easily have your various Models defined with a method to return HTML information. You don't (generally) want to return fully-baked HTML. But CSS ID or Class information is sometimes helpful.
class SiteUpdate( models.Model ):
page = models.ForeignKey(Page)
item_text = models.CharField(max_length=100)
item_css_class = models.CharField(max_length=64)
Now you can generate this into the template with a simple <div class="{{item.item_css_class}}">{{item.item_text}}</div> and use CSS to handle the formatting details that distinguish site update as opposed to a blog post.
The include template tag can take a variable containing the template to include, so you could loop through a sequence containing the various sub-templates and include them in turn, maybe using a dict to map friendly names to template filenames.

Categories