django admin get verbose name in template - django

I'm overriding the django admin/templates/admin/includes/fieldset.html
I want my checkbox labels to be wrapped around the checkbox, but I can't figure out a way to access the verbose name of the model. Normally I would just add a method to the model but since I'm doing this in the admin and want to do it for every model, everywhere without effort I was wondering if here was an easier way.
This is what I have so far:
{% if field.is_checkbox %}
<div class="checkbox">
<label for="{{ field.auto_id }}" class="vCheckboxLabel">
{{ field.field }}
{{ field.give_me_the_verbose_name_for_the_model_plsthx }}
</label>
{% if field.field.help_text %}
<p class="help-block">{{ field.field.help_text|safe }}</p>
{% endif %}
</div>
{% else %}
...

You can access verbose name by:
field._meta.verbose_name
But it works only in view, you haven't _meta in template.

Related

How to keep 2 fields using django forms

As django forms run a loop for the fields
{% for field in form %}
<div class="col-6">
{{ field.errors }}
{{ field.label_tag }}
{{ field }}
</div>
{% endfor %}
I actually want to have 2 fields, I found a cheap solution to this issue using Bootstrap4
I created the columns by using col-6 by which I get 2 fields in the row. But what if I want to make custom designs of forms in django ?
Personally i am using this method to show only fields i want and then have if statements for the way each field should be shown
{% for i in form %}
{% if i.name in 'title,address,city' (Fields you want to show) %}
{% for error in i.errors %}
<div>
<li><strong>{{ error|escape }}</strong></li>
</div>
{% endfor %}
<p>
<label>{{i.label}}:</label>
<input type="text" name="{{i.name}}" required id="id_{{i.name}}">
</p>
{% endif %}
{% endfor %}
And like that you can style it however you want and show only those you want to show

Override django form field

I've been research a lot about this, but don't get any answer accurate. Here's the deal: I want to override where forms.Field is used from my own, that is, where all classes that inherit from forms.Field, inherit from my own. Why? I like to add some properties that i'll use in every single field.
Anyone?
This is the code which i used, please keep in mind that this field is purely for text-fields, for passwords you have to manually override form value fields.
{% for field in form %}
<div class="custom_class_here ">
{% if field.errors%}
<div class="custom_class_here">
{{ field.errors }}
</div>
{% endif %}
{% if field.help_text %}
<p class="custom_class_here">{{ field.help_text|safe }}</p>
{% endif %}
<input type="{{ field.field.widget.input_type }}" name="{{ field.html_name }}" id="{{field.id_for_label}}" class="custom_class_here" placeholder="{{field.label}}" value= "{{field.value|default_if_none:''}}">
</div>
{% endfor %}
Also for checkbox, select, passwords dropdowns etc you have to write separate if conditions and and alter fields accordingly.
I referred Vitor's site

Django selectdatewidget how to render manually?

I'm trying to render a selectdatewidget in django out manually so I can customise with bootstrap. However I'm not clear on how I render out the indvidual inputs with the selectdatewidget?
class ProfileForm(forms.Form):
first_name = forms.CharField(max_length=30)
last_name = forms.CharField(max_length=30)
eighteen_years_from_now = (datetime.datetime.now().year - 18)
date_of_birth = FieldBuilder(User, 'date_of_birth', widget=SelectDateWidget(
years=range(eighteen_years_from_now, 1919, -1)))
template to render an individual field:
<div class="form-group">
<label for="{{ field.id_for_label }}" class="sr-only">
{{ field.label }}
</label>
{% if form.is_bound %}
{% if field.errors %}
{% render_field field class="form-control is-invalid" %}
{% for error in field.errors %}
<div class="invalid-feedback">
{{ error }}
</div>
{% endfor %}
{% else %}
{% render_field field class="form-control is-valid" %}
{% endif %}
{% else %}
{% render_field field class="form-control" placeholder=field.label %}
{% endif %}
{% if field.help_text %}
<small class="form-text text-muted">{{ field.help_text }}</small>
{% endif %}
</div>
The short answer is that you can't get the control needed, without overriding the inbuilt django template.
Thankfully Django 1.11 changed the widget system to use templates rather than python code making this easier to override.
From reviewing the templates in django/forms/templates/django/forms/widgets we can see that the select date widget loads the multiwidget template which for each subwidget loads the widget template:
{% for widget in widget.subwidgets %}{% include widget.template_name %}{% endfor %}
For select date widget this means the output is the 3 select tags (month, day, year) next to each other. This can't be eg made inline with bootstrap as each <select> needs to be wrapped in a div with the appropriate css class.
Templates can be overriden by following the django docs here:
https://docs.djangoproject.com/en/1.11/ref/forms/renderers/#overriding-built-in-widget-templates

Use field label as placeholder with django-widget-tweaks

I am using django-widget-tweaks and unable to figure out how to add a field variable as placeholder, like the following:
<div class="col-sm-10">
{{ field|append_attr:"class:form-control"|append_attr:"placeholder:field.label" }}
{% if field.help_text %}
<p class="help-block"><small>{{ field.help_text }}</small></p>
{% endif %}
</div>
field.label above does not evaluate and puts the string "field.label" as the placeholder on the page.
Some SO posts suggest registering a custom tag/filter which seems complicated for something this simple.
I am now using render_field to render the field instead of using template filters and it seems to work.
<div class="col-sm-10">
{% render_field field class="form-control" placeholder=field.label %}
{% if field.help_text %}
<p class="help-block"><small>{{ field.help_text }}</small></p>
{% endif %}
</div>
It seems form variables cannot be used within template filters and can only be used with render_field (though the django-widget-tweaks documentation doesnt say that explicitly).

Trying to access ModelForm field modelChoice choices in Django template

I'm generating ModelForms and want some granular control over how they are output in my template. Specifically, I need to add some markup to the end of each radio button in each of my select lists.
Code:
# order-form.html
{% load catname %}
<form id = "order-form">
{% for form in forms %}
<div id="gun-{{ forloop.counter }}">
{% for field in form.fields %}
<div id="{{ field }}-item" class="item">
<h3>{{ field|catname }}</h3>
{% for choice in form.field.choices %} {# <-- Help me out here #}
{{ choice.id }}
{{ choice.title }}
{% endfor %}
</div>
{% endfor %}
{% endfor %}
<button type="submit" id="standard-gun-form-submit">Continue to next step</button>
</form>
# views.py
def get_form(request):
if request.method == 'POST':
if request.POST['gun_type'] == 'standard':
forms = [StandardGunForm(prefix=p) for p in range(0,2)]
return render_to_response('main/order-form.html', {'forms' : forms,}, RequestContext(request))
# forms.py
class StandardGunForm(ModelForm):
def __init__(self, *args, **kwargs):
super(StandardGunForm, self).__init__(*args, **kwargs)
for field in self.fields:
if isinstance(self.fields[field], ModelChoiceField):
self.fields[field].empty_label = None
class Meta:
model = BaseGun
widgets = {
'FrameTuning' : RadioSelect(),
'FrameConnection' : RadioSelect(),
}
exclude = ('price')
Endgame: markup that looks like this
<form id="foo">
<div class="category">
<div class="item">
<input type="radio" name="srsbzns" value="1">Option 1</input>
<img src="http://placekitten.com/150/150">
<p>Other foo here</p>
</div>
<div class="item">
<input type="radio" name="srsbzns" value="2">Option 2</input>
<img src="http://placekitten.com/150/150">
<p>Other foo here</p>
</div>
<div class="item">
<input type="radio" name="srsbzns" value="3">Option 3</input>
<img src="http://placekitten.com/150/150">
<p>Other foo here</p>
</div>
</div>
</form>
From the shell, this returns what I want
>>> forms = [StandardGunForm(prefix=p) for p in range(0,2)]\
>>> forms[0].fields['frame_tuning'].choices.queryset
I'm surprised this is proving so challenging!
Bonus: I have DEBUG = True and Django Debug toolbar enabled. Is it possible to dump the variables to the browser, so I can see what this stuff looks like as I drill down?
Thanks!
I had to do something similar and started down this path as well. I wanted to create table rows from a ModelChoiceField where each column had a different field of the model instance (and then I'd allow filtering the table rows via JavaScript).
I couldn't find it in the Django docs, but a quick perusal of the Django source showed the way. You can get to the queryset to access the model instances like so:
<form action="{% url 'some_view' %}" method="post">
{% csrf_token %}
{% if form.non_field_errors %}
{{ form.non_field_errors }}
{% endif %}
{% for field in form %}
{{ field.label }}
{% if field.field.choices %}
{% for model_instance in field.field.choices.queryset %}
{{ model_instance.id }}
{% endfor %}
{% else %}
{{ field }}
{% endif %}
{% if field.errors %}
{{ field.errors|striptags }}
{% endif %}
{% endfor %}
<button type="submit">Submit</button>
</form>
However, at this point we've disassembled the shiny widget (in my case a CheckboxSelectMultiple) and must re-assemble the HTML form input using template code. I found no direct way to simultaneously iterate over the ModelChoiceField to access the model instance fields and get the HTML form tags for the choices.
Maybe there's a way, but I abandoned my attempt and built my own HTML form, handling all the POST data in a view. It ended up much easier that way. ModelForms are really nice and convenient, but using them for something they weren't built for can end up being more difficult.
I figured I'd post this in case anyone is trying to do it for some other reason. Hope it helps.
Very late, but I'm reading now and this is what it worked for me
{% for field in form %}
{% for x, y in field.field.choices %}
{{x}}
{{y}}
{% endfor %}
{% endfor %}
Where "x" is the id or code, and "y" is the readable value or title.
You can access the underlying model instance for each choice:
{% for choice, label in form.field_name.field.choices %}
{{ choice.value }}
{{ choice.instance }}
{{ choice.instance.instance_attribute }}
{{ label }}
{% endfor %}
{% for choice in form.field.choices %} {# <-- Help me out here #}
{{ choice.id }}
{{ choice.title }}
{% endfor %}
Look what you're doing here, you're literally trying to access a field called "field" every time in this loop, which presumably does not exist.
You need to take the field object you're iterating through, and access the choices attribute on that.
{% for field in form.fields %}
{% for choice in field.choices %}