Django Forms Template Design Classes

Django Forms Template design classes

If you just need all labels to have a particular class, the best way would be to change the markup and CSS slightly. Put a <div> with your class around the form:

<div class="field-title">
{{ form.as_p }}
</div>

and make the CSS definition as follows:

div.field-title label {
...
}

Django Forms Template design classes

If you just need all labels to have a particular class, the best way would be to change the markup and CSS slightly. Put a <div> with your class around the form:

<div class="field-title">
{{ form.as_p }}
</div>

and make the CSS definition as follows:

div.field-title label {
...
}

Formatting Django forms elements in html templates

class ContactForm(forms.Form):
name = forms.CharField(
widget=forms.TextInput(
attrs={
"class": "w3-input w3-border",
"type": "text",
"placeholder": "Name",
"name": "name",
}
),
max_length=100
)
email_address = forms.EmailField(
widget=forms.TextInput(
attrs={
"class": "w3-input w3-border",
"type": "text",
"placeholder": "Email",
"name": "email_address",
}
),
max_length=150
)
message = forms.CharField(
widget=forms.TextInput(
attrs={
"class": "w3-input w3-border",
"type": "text",
"placeholder": "Message",
"name": "message",
}
),
max_length=2000

)
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<div class="w3-col m6">
<form action="" method="post">
{% csrf_token %}
<div class="w3-row-padding" style="margin:0 -16px 8px -16px">
<div class="w3-half">
{{ form.name }}
</div>
<div class="w3-half">
{{ form.email_address }}
</div>
</div>
{{ form.message }}
<button class="w3-button w3-black w3-section w3-right" type="submit">SEND</button>
</form>
</div>

Add class to specific fields in django forms

If you want anything even remotely beyond what Django gives you with as_p, you should specify the fields yourself. You'll get much more control without having to hack around. A simple template tag like display_field will allow you just to specify each field, its label and errors with a single tag. Then you can group the fields yourself using the HTML element meant for that: a fieldset.

<fieldset class="my_fieldset">
{% display_field form.field1 %}
{% display_field form.field2 %}
</fieldset>

Django form template

You can add the class to a wrapper around the field. Django also does this by itself when defining classes in forms.py or views.py

{% for field in form %}
<p {% if field.errors %}class="error"{% endif %}
{{ field }}
</p>
{% if field.errors %}{{ field.errors }}{% endif %}

{% endfor %}

Unfortunately this seems to be the only way.
Even when Django adds the classes itselt, it prefers to add them to a wrapper of some sort.

http://docs.djangoproject.com/en/dev/ref/forms/api/#more-granular-output

Scroll down to read about the new thing in 1.2 about adding css classes.
Using this, you can just use form.as_p (or whatever suits you) as the

elements will have all the classes as you define them.
Hope this was a little bit of help.

Django/Python Model/Form class design

I was able to resolve my design using django formsets https://docs.djangoproject.com/en/1.10/topics/forms/formsets/

I ended up with 3 forms (TeamForm, PlayerForm, and PlayerWeekForm), with the PlayerForm instantiated in the TeamForm, and the PlayerWeekForm instantiated in the PlayerForm.

The resulting screen looks like this:
Sample Image

So, to be complete, the view looks like this:

def detailform(request, team_id):
team = get_object_or_404(Team, pk=team_id)
print team_id
print team
PlayerFormSet = formset_factory(PlayerForm, formset=BaseFormSet, extra=0)

team_players = team.players.all()

player_data = [{'name' : p.user.first_name+" "+p.user.last_name, 'player' : p } for p in team_players]

if request.method == 'POST':
print request.POST
pi = 0
for player in team.players.all():
i=0
for week in team.week_set.all():
wd = request.POST.getlist('form-{}-available'.format(i))
print wd
pws_t = player.playerweek_set.get(player=player, week=week );
pws = get_object_or_404(PlayerWeek, pk=pws_t.pk)
pws.available = wd[pi]
pws.save()
i=i+1
pi=pi+1

player_formset = PlayerFormSet(initial=player_data)
team_form = TeamForm(team=team, formset=player_formset)

context = { 'team_form' : team_form, 'team' : team }

return render(request, 'dtm/team_form.html', context)

and the forms look like this:

class PlayerWeekForm(forms.Form):

AVAILABLE_CHOICES = ( ('Y', 'Yes'), ('N', 'No'), ('?', '?'), ('S1', 'S1'), ('S2', 'S2'), ('D1', 'D1'), ('D2', 'D2'), ('D3', 'D3'))
available = forms.ChoiceField(choices=AVAILABLE_CHOICES)

class PlayerForm(forms.Form):
def __init__(self, *args, **kwargs):
self.player = kwargs['initial']['player']

super(PlayerForm, self).__init__(*args, **kwargs)

self.fields['name'] = forms.CharField(max_length=30,widget=forms.TextInput(), disabled=True)

PlayerWeekFormSet = formset_factory(PlayerWeekForm, formset=BaseFormSet, extra=0)
pwdata = [{'available' : pwf.available_type} for pwf in self.player.playerweek_set.all()]
self.playerweek_formset = PlayerWeekFormSet(initial = pwdata)

class TeamForm(forms.Form):
def __init__(self, *args, **kwargs):
self.team = kwargs.pop('team', None)
self.player_formset = kwargs.pop('formset', None)

super(TeamForm, self).__init__(*args, **kwargs)

self.fields['name'] = forms.CharField(max_length=30,initial = self.team.name, widget=forms.TextInput(), disabled=True)

Ultimately I will subclass BaseFormSet as necessary to do validation on the formset.

How To Provide A Class To Fields In A Django Template?

django-widget-tweaks

I'm using django-widget-tweaks module for set HTML attribute in templates.

installation

  1. install module using pip install django-widget-tweaks
  2. add to INSTALLED_APPS in settings.py
INSTALLED_APPS = [
...
'widget_tweaks',
...
]

  1. {% load widget_tweaks %} in templates file

usage

in templates code:

{% load widget_tweaks %}
...

{% for field in form %}
{% render_field field class="txtb" %}
...

in HTML, looks like this:

<input class="txtb" ... ...>

reference django-widget-tweaks github page for more information.


manually

Detailed description is in here

forms.py:

class YourForm(forms.ModelForm):
modelfield = forms.CharField(
...,
widget=forms.TextInput(
attrs={
'class': 'txtb'
}
}
)

class Meta:
model = ...
fields = ...


And I have a lot of information about django to simpleisbetterthancomplex.com

django-widget-tweaks also learned here



Related Topics



Leave a reply



Submit