Get only one field from django forms in template - python

I have one form :
class FormLogin(forms.Form):
email = forms.EmailField(max_length=150)
name = forms.CharField(max_length=20)
How can I put just email field in my template ?
I tried this :
{{ form.fields.email }}
But it returns <django.forms.fields.CharField object at 0x00000000043BCEB8>.

You can just use:
{{ form.email }}

You don't need to use fields.
Use:
{{ form.email }}

Related

Can't use CKEDITOR in django template

I am using a form without a model class.
class ClubWallForm(forms.Form):
title = forms.CharField(label='Post title', max_length=100)
description = RichTextField()
imgURL = forms.CharField(label='Post image url', max_length=100)
filefield = forms.FileField( label='Select a file',validators=[validate_file_extension] )
In my template I used
` {% for field in form %}
<div class="fieldWrapper">
{{ field.errors }}
{{ field.label_tag }}: {{ field }}
</div>
{% endfor %}`
CKEDITOR is not geting displayed in my template.
This is what I am getting.
Inside my views it tried to use ipdb and found that the form has only fields title imgurl and filefield .
You have two issues:
RichTextField is a model field. RichTextFormField is the corresponding form field.
You're not handling the form media in the template. This is outlined in the documentation.
You can also use widget tweaks
First install it by
pip install django-widget-tweaks
then load it in your template file with
{% load wiget_tweaks %}
also use this in your site header
<script src="https://cdn.ckeditor.com/4.16.1/standard/ckeditor.js"></script>
now you can set your class to your form with out change it in forms.py
so the themplate file should be like this
{{ form.description|add_class:"ckeditor" }}
Second way is:
just use this code in themplate file
{{ form.media }}
{{ form.description }}
Finally I got an answer from my friend.
it was to replace
description = RichTextField()
with
description = forms.CharField(label='Description',
widget=forms.Textarea(attrs={'class': 'ckeditor'}))
inside forms.py
and it is working

Convert user.id to user.username in Django template

I am implementing the very cool third party package Django-Simple-History into a project. Per the documentation I'm using the middleware to store which user makes changes to an object. This makes it easy to iterate over in the template like:
{% for x in object.history.all %}
{{ x.history_date }}, {{ x.history_user_id }} <br />
{% endfor %}
I am trying to use the available user.id to get the correlating user.username in the template. Any suggestions? (I'm still pretty new to Django/Python) Thanks!
history_user holds the ForeignKey for the related user.
You can use: {{ x.history_user.username }}

How to access form date fields in template

I want to render a form in Django. In normal case, you access fields like this:
{{ form.name }}
But I'm using date field with SelectDateWidget widget. This widget has different field for year,month and day.
How could I access these fields one by one?
{{ form.date.year }} or
{{ form.date.0 }} or
{{ form.date_year }} etc. doesn't work.
Try this:
{{ form.date|date:"Y" }}
You can take a look at the complete docs here: https://docs.djangoproject.com/en/1.10/ref/templates/builtins/

How to access object attribute via django variable?

I want to convert this code to something more inheritable to avoid coding. Consider that my code is simple and simple answer is need.
{{ entity.name }}
{{ entity.description }}
I want to convert to such code:
{% for attribute in attributes %}
{{ entity ??? }} == entity.get_attr(attribute)
{% end for %}
What is valid syntax for it?
The easiest example with filter:
# templatetags.ry
from django import template
register = template.Library()
#register.filter
def get_attr(object, name):
return getattr(object, name, '')
Your template:
{% load templatetags %}
{% for attribute in attributes %}
{{ entity|get_attr:attribute }}
{% end for %}

WTForms: nested form field, UndefinedError: 'unicode object' has no attribute 'label'

My form model is defined like this:
from com.example.cms.forms import FieldList as MyAppFieldList
from flask_wtf import Form
from wtforms import fields
from wtforms import validators
class FacebookPostTranslationForm(Form):
language = fields.StringField('Language', [validators.InputRequired(), validators.Length(min=2, max=2)])
title = fields.TextAreaField('Title', [validators.InputRequired()])
description = fields.TextAreaField('Description', [validators.InputRequired()])
linkUrl = fields.StringField('Link', [validators.InputRequired(), validators.URL()])
pictureUrl = fields.StringField('Picture', [validators.InputRequired(), validators.URL()])
class FacebookPostTemplateForm(Form):
name = fields.StringField('Name', [validators.InputRequired()])
title = fields.TextAreaField('Title', [validators.InputRequired()])
description = fields.TextAreaField('Description', [validators.InputRequired()])
linkUrl = fields.StringField('Link', [validators.InputRequired(), validators.URL()])
pictureUrl = fields.StringField('Picture', [validators.InputRequired(), validators.URL()])
translations = MyAppFieldList(fields.FormField(FacebookPostTranslationForm), [validators.Optional()])
class FacebookPostTemplateCreateForm(FacebookPostTemplateForm):
pass
class FacebookPostTemplateUpdateForm(FacebookPostTemplateForm):
pass
and then inside HTML template I have:
<span id="translationFieldsetHolder">
{% for translation in form.translations.entries %}
<fieldset class="translationFieldset">
<legend>{% if translation.language.data %}{{ translation.language.data|upper }}{% else %}Add{% endif %} Translation</legend>
{{ render_field(translation.language) }}
{{ render_field(translation.title, rows=5) }}
{{ render_field(translation.description, rows=5) }}
{{ render_field(translation.linkUrl) }}
{{ render_field(translation.pictureUrl) }}
{{ translation.csrf_token }}
</fieldset>
{% endfor %}
</span>
Everything but translation.description renders fine. Namely this line causes problems:
{{ render_field(translation.description, rows=5) }}
If I replace description with title it works fine (although it renders title twice instead of title plus description).
With description I get the following error:
{{ field.label(class="control-label") }}
UndefinedError: 'unicode object' has no attribute 'label'
in the macro that starts with:
{% macro render_field(field) %}
<div class="control-group {% if field.errors %}error{% endif %}">
{{ field.label(class="control-label") }}
I'm quite new to Python or WTForms. Is there anything special with description field name that could cause some problems / clashes?
I can see that the data is correctly delivered to the controller via the web service. There is nothing suspicious in the value of this field.
The sample code to be run. It was extracted from the original sources so at some places it is a mess.
If I change the name of the field it works :(
But it implies I would have to either change it on the web service or somewhere in Python code.
Thank you.
Field itself has description kwarg
class Field(object):
def __init__(self, label=None, validators=None, filters=tuple(),
description='', id=None, default=None, widget=None,
_form=None, _name=None, _prefix='', _translations=None):
What you are doing is adding into FormField(Field) object that also has description inside
class FacebookPostTranslationForm(Form):
description = fields.TextAreaField('Description', [validators.InputRequired()])
In template when You call translation.description WTForms is returning Field.description instead of FacebookPostTranslationForm.description
Hope that helps :)

Categories

Resources