Django Tables2 Filter - django

I am trying to display a table with filter using Django tables 2 and crispy forms.
I have the following files:
filter.py
import django_filters
from .models import Poste
class PosteFilter(django_filters.FilterSet):
id = django_filters.CharFilter(lookup_expr='icontains')
status = django_filters.CharFilter(lookup_expr='icontains')
address = django_filters.CharFilter(name='address', lookup_expr='icontains')
atualizado_em = django_filters.CharFilter(lookup_expr='icontains')
class Meta:
model = Poste
fields = {'id', 'status', 'address', 'atualizado_em',}
forms.py
from django import forms
from .models import Poste
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, ButtonHolder, Submit
class PosteListFormHelper(FormHelper):
model = Poste
form_tag = False
form_style = 'inline'
layout = Layout(
'id',
'status',
'address',
'atualizado_em',
Submit('submit', 'Filtrar'),
)
table.py
import django_tables2 as tables
from .models import Poste
class PosteTable(tables.Table):
class Meta:
model = Poste
# add class="paleblue" to <table> tag
attrs = {'class': 'paleblue'}
fields = ('id', 'status', 'address', 'atualizado_em')
per_page: 25
As a result, I get this:
What I want is:
exclude the word "contains" in the label
have the filter form fields inline
I tried many ways to do that without success.

It looks as if you can set the label by setting label in the CharFilter:
class PosteFilter(django_filters.FilterSet):
id = django_filters.CharFilter(lookup_expr='icontains', label='Id')
status = django_filters.CharFilter(lookup_expr='icontains', label='Status')
...
It looks as if you could also change the FILTERS_VERBOSE_LOOKUPS setting, although the docs warn that it's an advanced setting and subject to change.
from django_filters.conf import DEFAULTS
def FILTERS_VERBOSE_LOOKUPS():
verbose_lookups = DEFAULTS['VERBOSE_LOOKUPS'].copy()
verbose_lookups['icontains'] = '' # Don't add any extra text like 'contains'
return verbose_lookups

I use FormHelper to make the form inline
class UnitFilterFormHelper(FormHelper):
form_method = 'GET'
form_style = 'inline'
form_show_labels = False
label_class = 'col-md-1'
field_class = 'col-md-11'
layout = Layout(
HTML('<hr>'),
Row(
Column('branch', css_class="col-md-10"),
Column(Submit('submit', _('Apply Filter')), css_class="col-md-2"),
# css_class="form-inline",
),
)

Related

How to add Widgets to UpdateView in Django

I need to add this widget to the django UpdateView,
class tlistUpdate(LoginRequiredMixin,UpdateView):
fields = ('title', 'thumbnail', 'content', 'tags')
model = htmlpage
template_name = 'blog/create_form.html'
Tried adding
widgets = {
'content': SummernoteWidget(),
}
and
content = forms.CharField(widget=SummernoteWidget())
But it did't work.
The UpdateView is not constructed to handle advanced form construction. The idea is that you use fields if you aim to construct a simple (standard) Form.
You can simply construct a ModelForm and use that form in your CreateView/UpdateView:
# app/forms.py
from django import forms
class HtmlPageForm(forms.ModelForm):
class Meta:
model = HtmlPage
fields = ('title', 'thumbnail', 'content', 'tags')
widgets = {
'content': SummernoteWidget
}
In your views.py you can then use the form by setting the form_class attribute [Django-doc]:
# app/views.py
from app.forms import HtmlPageForm
class TlistUpdate(LoginRequiredMixin,UpdateView):
model = htmlpage
form_class = HtmlPageForm
template_name = 'blog/create_form.html'
Note: normally a Django models, just like all classes in Python are given a name in PerlCase, not snake_case, so it should be: HtmlPage instead of htmlpage.

How to save signed in username with the form to database? Django

All other data is saved ideally but as shown below, the user id part shows as a pull down bar and a null value which should be a signed-in username.
What's wrong with my code?
The database page
Here's my code.
views.py
from .models import Markers
from .forms import AddMarkersInfo
from django.http import HttpResponse
def addinfo(request):
if request.method == 'POST':
mks = AddMarkersInfo(request.POST)
if mks.is_valid():
submit = mks.save(commit=False)
submit.user = request.user
submit.save()
name = mks.cleaned_data['name']
address = mks.cleaned_data['address']
description = mks.cleaned_data['description']
type = mks.cleaned_data['type']
lat = mks.cleaned_data['lat']
lng = mks.cleaned_data['lng']
Markers.objects.get_or_create(name=name, address=address, description=description, type=type, lat=lat, lng=lng)
return render(request, 'home.html', {'mks': mks })
else:
mks = AddMarkersInfo()
return render(request, 'home.html', {'mks': mks})
models.py
from django.db import models
from django.contrib.auth.models import User
from django.conf import settings
from django.contrib.auth import get_user_model
def get_sentinel_user():
return get_user_model().objects.get_or_create(username='deleted')[0]
class Markers(models.Model):
User = settings.AUTH_USER_MODEL
use_id= models.ForeignKey(User, null=True, on_delete=models.SET(get_sentinel_user),)
name = models.CharField(max_length=60,default = 'name')
address = models.CharField(max_length=100,default = 'address')
description = models.CharField(max_length=150, default='description')
types = (
('m', 'museum'),
('s', 'school'),
('r', 'restaurant'),
('o', 'other'),
)
type = models.CharField(max_length=60, choices=types, default='museum')
lat = models.IntegerField()
lng = models.IntegerField()
forms.py
from django import forms
from maps.models import Markers
class AddMarkersInfo(forms.ModelForm):
class Meta:
model = Markers
fields = ['name','address','description', 'type','lat','lng',]
Well, first of all, you should remove the lines from django.contrib.auth.models import User and User = settings.AUTH_USER_MODEL in models.py if you are going to use settings.AUTH_USER_MODEL. You should use only one of the two.
And you can change your field to:
use_id= models.ForeignKey(settings.AUTH_USER_MODEL, ...
Secondly, it seems like you are duplicating the creation. The lines
submit = mks.save(commit=False)
submit.user = request.user
submit.save()
already create an Markers instance, so there is no need to call Markers.objects.get_or_create(... after that.
And, according to you models, the field should be submit.use_id instead of submit.user.
Now, if I understand your question correctly you want to make the use_id field read-only in your form/template.
I don't know why that field is even showing up in your form, since it is not listed in your forms Meta.fields.
You could try something like setting the widget attribute readonly:
class AddMarkersInfo(forms.ModelForm):
class Meta:
model = Markers
fields = ['use_id', 'name', 'address', 'description', 'type', 'lat', 'lng']
widgets = {
'use_id': forms.Textarea(attrs={'readonly': 'readonly'}),
}

add my own class in admin field django-cms

Hi everyone Y create my own app in djando CMS, now I want to add my own class and id's to my field.. y try this, but I don't obtain any successful result.
in my model.py I have this
class Entry(models.Model):
TYPES_CHOICES = (
('none', 'not specified'),
('s', 'Series'),
('mb', 'Multiples Bar'),
('b', 'Bar suggestion'),
)
app_config = AppHookConfigField(HealthConfig)
code = models.CharField(blank=True, default='', max_length=250)
url_suggestion = models.CharField(blank=True, default='', max_length=250, verbose_name="URL for Suggestion" )
health_placeholder = PlaceholderField('health_info')
objects = AppHookConfigManager()
def __unicode__(self):
return self.url
class Meta:
verbose_name_plural = 'entries'
and now in my form.py I have this
from django import forms
from .models import Entry
class EntryForm(forms.ModelForm):
class Meta:
model = Entry
fields = '__all__'
def __init__(self, *args, **kwargs):
super(EntryForm, self).__init__(*args, **kwargs)
self.fields['code'].widget.attrs={
'id': 'my_code',
'class': 'code_class',
}
finally my admin.py is like this
from django.contrib import admin
from cms.admin.placeholderadmin import PlaceholderAdminMixin
from .cms_appconfig import HealthConfig
from .models import Entry
from .forms import EntryForm
from aldryn_apphooks_config.admin import ModelAppHookConfig, BaseAppHookConfig
class EntryAdmin(ModelAppHookConfig, PlaceholderAdminMixin, admin.ModelAdmin):
# pass
fieldsets = (
('General data', {
'fields':('app_config','chart', 'url',('count', 'code', 'start'))
}),
('Suggestion',{
'classes':('collapse', 'suggestion',),
'fields':('url_suggestion',('key1_suggestion_name','key1_suggestion'),('key2_suggestion_name','key2_suggestion'), 'primary_suggestions')
}),
)
list_display =('app_config' ,'url', 'chart');
list_filter = (
'app_config',
)
form = EntryForm
class Media:
js = ('health/js/admin/healthAdmin.js',)
css = {
'all': ('health/css/admin/admin_area.css',)
}
admin.site.register(Entry, EntryAdmin)
any idea is I missing something, after that, I do a migrate of the component again.
Thanks in advance!
You can specify a custom form for admin using the form attribute of ModelAdmin.
So using the example from the docs linked below, that would look like;
from django import forms
from django.contrib import admin
from myapp.models import Person
class PersonForm(forms.ModelForm):
class Meta:
model = Person
exclude = ['name']
class PersonAdmin(admin.ModelAdmin):
exclude = ['age']
form = PersonForm
https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.form
So in your admin.py you'd need something like;
from .forms import EntryForm
class EntryAdmin(admin.ModelAdmin):
form = EntryForm

Add descriptive text to the right of field in Django admin

I have a DecimalField in my model that I'd like to show up in the admin interface with a unit to the right of the field, like so:
I think if I add help_text to the field, that will show up below the field. Is there a way to specify it to show up to the right?
You can handle it with help_text from the forms, overwrite your field in the form, such as the css.
from django.db import models
from django.contrib import admin
from django import forms
from your.models import Post
class PostForm(forms.ModelForm):
ethanol = forms.FloatField(
label='This is Ethanol',
max_value=10,
min_value=0,
widget=forms.NumberInput(
attrs={
'class': 'whatever',
'style': 'position:relative'
}
),
help_text='<span style="position:absolute;right:0">g/mL</span>'
)
class Meta:
model = Post
fields = '__all__'
class PostAdmin(admin.ModelAdmin):
form = PostForm
list_display = ['ethanol', 'id']
admin.site.register(Post, PostAdmin)

Django - Admin: list_display TextField

I'm trying to display the first 10 characters of a TextField on a list_display.
Is it possible in the admin interface ?
You can define a callable that returns the first 10 characters of the field, and add that to list_display.
More information see the Django docs for list_display.
myapp/admin.py
from django.contrib import admin
from django.utils.text import Truncator
from django.db import models
from .models import Product
def truncated_name(obj):
name = "%s" % obj.name
return Truncator(name).chars(70)
class ProductAdmin(admin.ModelAdmin):
list_display = ['id', truncated_name, 'category', 'timestamp',]
list_display_links = [truncated_name]
list_filter = ['category']
class Meta:
model = Product
You can also override the fields like so:
formfield_overrides = {
models.CharField: {'widget': TextInput(attrs={'size': '20'})},
models.TextField: {'widget': Textarea(attrs={'rows': 1, 'cols': 40, 'style': 'height: 1.5em;'})},
}