Django Crispy Forms, Bootstrap, helper.label_class and helper.field_class not working - css

I have a problem with the crispy forms framework, setting the field_class and label_class attributes is not making a difference to the layout. I am using Bootstrap3, and all of the css files can be used elsewhere on my site (ie they are being picked up successfully in the static directory).
forms.py
class LoginForm(forms.Form):
username = forms.CharField()
password = forms.CharField(widget=forms.PasswordInput)
helper = FormHelper()
helper.form_class = 'form-horizontal'
helper.label_class = 'col-lg-2'
helper.field_class = 'col-lg-10'
helper.layout = Layout(
'username',
'password',
Submit('submit', 'Log Me In', css_class='btn btn-success'),
)
login.html
{% extends "base.html" %}
{% load crispy_forms_tags %}
{% block content %}
{% crispy form %}
{% endblock %}
Upon inspecting element in my browser, the col-lg-2 and col-lg-10 CSS classes are simply NOT being applied to the labels and fields respectively...

You should place all the helper logic under the __init__ method:
class LoginForm(forms.Form):
username = forms.CharField()
password = forms.CharField(widget=forms.PasswordInput)
def __init__(self, *args, **kwargs):
super(LoginForm, self).__init__(self, *args, **kwargs)
self.helper = FormHelper()
self.helper.form_class = 'form-horizontal'
self.helper.label_class = 'col-lg-2'
self.helper.field_class = 'col-lg-10'
self.helper.layout = Layout(
'username',
'password',
Submit('submit', 'Log Me In', css_class='btn btn-success'),
)

Related

django-tables2 to used with django-modeltranslation showing all the fields when listed

I am using django-tables2 with django-modeltranslation in one of my new projects. The site is using localization for english and french.
If I render the table directly in html everything works fine, but django_tables2 seems to pour everything out, ignoring the localization request.
Django-tables2 has a "localize/unlocalize" option for multilingual sites but it does not seem to work with django-modeltranslation.
Here is my setup.
models.py
class DataSet(models.Model):
name = models.CharField(max_length=255)
source = models.CharField(max_length=255, null=True)
data_type = models.CharField(max_length=255, null=True)
translation.py
#register(DataSet)
class DataSetTranslationOptions(TranslationOptions):
fields = (
"name",
"source",
"data_type",)
tables.py
class DataSetTable(tables.Table):
name = tables.Column(order_by="name")
class Meta:
model = DataSet
sequence = (
"name",
"source",
"data_type",)
unlocalize = ("id",)
localize = (
"name",
"source",
"data_type",)
datasets.html
{% load i18n %}
{% load render_table from django_tables2 %}
{% block content %}
{% render_table table %}
{% endblock content %}
This table is rendered as follows:
name
source
data_type
name_en
name_fr
source_en
source_fr
data_type_en
data_type_fr
content
content
content
content
content
content
content
content
content
content
content
content
content
content
content
content
content
content
Please let me know what I am missing.

How can i style my django filter with bootstrap or CSS

i'm new to django here and still learning. So, i created a filter using django-filter and i didn't know how to style it (bootstrap or CSS) because i really don't like the default styling. Can anyone help me with it? i already googled it but didn't find anything useful.
filters.py
`
class CompLink_Filter(django_filters.FilterSet):
start_date = DateFilter(field_name="date_added", label='Date ajout' ,lookup_expr='gte')
company_name = CharFilter(field_name='company_name', label='Nom Entreprise' ,lookup_expr='icontains')
sector = CharFilter(field_name='sector',label='Secteur' , lookup_expr='icontains')
size = CharFilter(field_name='size', label='Taille' ,lookup_expr='icontains')
phone = CharFilter(field_name='phone', label='Téléphone' ,lookup_expr='icontains')
employees_on_linkedin = CharFilter(field_name='employees_on_linkedin', label='Employés sur Linkedin :' ,lookup_expr='icontains')
type = CharFilter(field_name='type', label='Type' ,lookup_expr='icontains')
founded_in = CharFilter(field_name='founded_in', label='Fondée En' ,lookup_expr='icontains')
specializations = CharFilter(field_name='specializations', label='Spécialisations' ,lookup_expr='icontains')
class Meta:
model = Comapny_Profile
fields= '__all__'
exclude= ['company_link','website','head_office','address']`
displaying the filter in my template:
<form class="" action="" method="get">
{% for field in myFilter.form %}
<div class="fieldWrapper">
{{ field.errors }}
{{ field.label_tag }} {{ field }}
{% if field.help_text %}
<p class="help">{{ field.help_text|safe }}</p>
{% endif %}
</div>
{% endfor %}
<button class="btn btn-primary" type="submit" name="button">Recherche</button>
</form>
You could use jQuery or javascript to manipulate the DOM. When the tags are created you can style it. For example.
$("input").addClass("form-group");

Cannot write data to db in Flask

I am working on a small reading tracking app in Flask. I cannot seem to write data from one of my routes, below:
#app.route('/add_book', methods=['GET', 'POST'])
#login_required
def add_book():
form=BookForm()
if request.method=='POST':
if form.validate_on_submit():
book=Book(
title=form.title.data,
author=form.author.data,
# category=form.category.data,
# added_on=form.added_on.data,
# done=form.done.data,
user_id=current_user
)
db.session.add(book)
db.session.commit()
flash('Book added')
return redirect(url_for('books'))
else:
flash('ERROR. The book not added.')
return render_template('add_book.html', form=form)
This is the corresponding HTML:
{% extends "layout.html" %}
{% block content %}
{% if form %}
<form action="{{ url_for('add_book') }}" method="post">
{{ form.hidden_tag() }}
{{ form.title.label }}<br>
{{ form.title() }}<br>
{{ form.author.label }}<br>
{{ form.author(cols=32, rows=4) }}<br>
<!-- {{ form.category.label }}<br>
{{ form.category() }}<br> -->
{{ form.submit() }}
</form>
{% endif %}
{% endblock %}
When the page renders, the label and forms for the book and author appear, however on clicking Submit, the data does not get saved.
The code section is similar to that for registering a user and I am stuck on what to do because I cannot see any errors. I am using SQLite as a database.
Here is the book model:
class Book(db.Model):
__tablename__='books'
id=db.Column(db.Integer, primary_key=True)
title=db.Column(db.String(100))
author=db.Column(db.String(50))
# category=db.Column(db.String(50))
added_on=db.Column(db.DateTime, index=True, default=datetime.utcnow)
done=db.Column(db.Boolean, default=False)
user_id=db.Column(db.Integer, db.ForeignKey('users.id'))
def __init__(self, title, author, added_on, done, user_id):
self.title=title
self.author=author
self.added_on=added_on
self.done=done
self.user_id=user_id
def __repr__(self):
# return '<Book: Title - {0}, Author - {1}, Category - {2}>'.format(self.title, self.author, self.category)
return '<Book: Title - {0}, Author - {1}>'.format(self.title, self.author)
The current_user is a user proxy giving access to all user attributes or use something like this How to track the current user in flask-login?
a quick solution would be to change this line
user_id = current_user
into this
user_id = current_user.id
Update:
ok, I got it working. You need the following fixes, each of them leads to trouble with form validation and or committing to database:
- use current_user.id in your book object as I said earlier.
- removed the init method in books model. I'm not sure what the added value is at the moment, I'm getting error messages about fields added on and done which are not on the form. I haven't taken the time to look into it further.
- just go for if request.method=='POST' as you don't need both. The form will be checked for validation anyways.
tip: don't forget to create a requirements file (pip freeze --> requirements.txt), that makes it a lot easier to reinstall in a new virtual environment.

Save charts on server

I have a symfony3 project with working Highcharts functions implemented through the ob/highcharts-bundle and I really like the way the generated charts look with a custom theme.
I would like to be able to run a script on the server that generates an email and along the way builds the charts that I need (complete with my custom theme) and saves to the server so I can link to them from the email.
I've previously done this in pChart, and saving an image on the server from a script is as easy as $myPicture->autoOutput('myimage.png'). While that's easy, I prefer the look of charts from Highcharts.
Is there a similar simple way to do this something like this using Highcharts?
My scripts look like this:
// Controller
$xdata = array(1, 2, 3, 4);
$data_series = array(
0 => array(
"name" => "Series 1",
"data" => array(
0 => 2.0, 1 => 0.0, 2 => 5.0, 3 => 2.3, 4 => 0.45, 5 => 0.4
)
)
);
$ob = new Highchart();
$ob->chart->renderTo('trendchart'); // id of the div where the chart gets rendered
$ob->title->text('Chart title');
$ob->xAxis->categories($xdata);
$ob->series($data_series);
return $this->render('dashboard/main.html.twig', [
'trendChart' => $ob,
]);
and I render this in a twig template:
// twig template
{% extends 'base.html.twig' %}
{% block javascripts %}
{{ parent() }}
<script src="//code.highcharts.com/highcharts.js"></script>
<script src="//code.highcharts.com/modules/exporting.js"></script>
<script src="{{ asset('js/highchartThemes/mytheme.js') }}"></script>
<script>
{{ chart(trendChart) }}
</script>
{% endblock %}
{% block body %}
<div id="trendchart"></div>
{% endblock %}
What I'm hoping for is to make a call from my controller like:
$ob->save('myimage.png');
Does anyone know of a simple/clean way to do something like this?

How can I print Google Books api description?

Hie I am trying to get the synopsis and other items like author and published date printed. But I am Able to achieve this only with certain search terms, an error occurs with other words or terms
Key "description" for array with keys "title, subtitle, authors, publishedDate, industryIdentifiers, readingModes, pageCount, printType, categories, maturityRating, allowAnonLogging, contentVersion, imageLinks, language, previewLink, infoLink, canonicalVolumeLink" does not exist.
I am using symfony and twig. this is what the twig file looks like :
{% for item in items %}
<article>
<img src="{{ item.volumeInfo.imageLinks.thumbnail}}"/>
<h4>{{ item.volumeInfo.title}}</h4>
{{ item.volumeInfo.description }}
<strong> {{ item.volumeInfo.publishedDate }}</strong><br/>
<b>{{ item.volumeInfo.authors | join }}</b>
</article>
What am I doing wrong? why does this work only sometimes ? how can I make it work correctly all the time?
class GoogleBooksController extends Controller
{
public function getVolumeAction($title)
{
$client =new client();
$response = $client- >get("https://www.googleapis.com/books/v1/volumes?q=$title");
$data=$response->json();
$items=$data['items'];
return $this->render('BookReviewBundle:GoogleBooks:volume.html.twig', array('items'=>$items
// ...
)); }
Thanks
I belive the description field is not mandatory, so you can do follow
{% if item.volumeInfo.description is defined %}
{{ item.volumeInfo.description }}
{% endif %}

Resources