Hello Im trying to implement chosen.js into my Django project and so far it works great. I only have one issue which I cannot solve. I have a model where "language" is a ChardField. I wanted to let the User choose more than one language so I tried to use chosen Multiple. Since a Charfield can only hold one Value so I used Django Multiselect. Now the Chosen.js is not working anymore and I have no idea what to do.
Models:
from multiselectfield import MultiSelectField
class UserProfile(models.Model):
language = MultiSelectField(verbose_name=_(u"Content Language"),
max_length=40, choices=settings.LANGUAGES,default='en')`
Forms:
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields=[
'language',
.....
]
Template:
{% load widget_tweaks %}
{% csrf_token %}
<span>Content language {{ form.language|add_class:"chosen-select" }}</span>
So the question is how do I get the normal chosen.js input field to a multiple chosen field (with Django)? I know there is the possibility to add a multiple field to the forms but this messes up my hole code.
I implemented the chosen multi select by the following:
Forms
class select_language(ModelForm):
#Get data for choice boxes
language_results = language.objects.all()
select_language = forms.ModelMultipleChoiceField(
queryset=language_results,
widget = forms.SelectMultiple(attrs={
'placeholder': "Choose the users(s)",
'class': 'chosen-select',
'multiple tabindex': '4',
}),
)
Template:
....
{% load static %}
<link rel="stylesheet" href="{% static 'chosen.css' %}">
<link rel="stylesheet" href="{% static 'prism.css' %}">
....
{{ select_language.select_language }}
<script type="text/javascript" src="{% static 'chosen.jquery.js' %}"></script>
<script type="text/javascript" src="{% static 'docsupport/prism.js' %}"></script>
<script type="text/javascript" src="{% static 'docsupport/init.js' %}"></script>
Of course you will need to update the locations for the static files. Hopefully this is a good starting direction.
Related
I have a non-admin form in which I'd like to use filter_horizontal on. I have read this which does much more than what I want (I only want the filter_horizontal). I wanted to check to see if anyone has come up with a simpler (more current) way to just implement the filter_horizontal.
So here is the code:
class County(models.Model):
"""County Names"""
name = models.CharField(max_length=64)
state = USStateField(null=True)
class Company(models.Model):
"""The basics of a company"""
name = models.CharField(max_length = 100)
counties = models.ManyToManyField(County,blank=True, null=True)
Then our form currently look like this. I thought this would work..
from django.contrib.admin.widgets import FilteredSelectMultiple
class RaterCompanyForm(ModelForm):
class Meta:
model = RaterOrganization
exclude = ('remrate_projects',)
widgets = {'counties': FilteredSelectMultiple(verbose_name="Counties",
is_stacked=True,) }
class Media:
css = {'all':['admin/css/widgets.css']}
js = ['/admin/jsi18n/']
BTW: I understand this may be a duplicate of this but his question wasn't answered. I've done plenty of homework here and here but neither of these appear to work.
I know this thread is old, but hopefully this info will help someone else who stumbles upon this page like I did.
After much pain and suffering, I was able to get this to work with Django 1.4. Like rh0dium, I tried all those articles, but had to make a lot of tweaks.
You don't have to do anything special with the ModelForm, but you do have to include all these js and css files in the template:
<script type="text/javascript" src="/admin/jsi18n/"></script>
<script type="text/javascript" src="{{ STATIC_URL }}admin/js/core.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}admin/js/jquery.min.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}admin/js/jquery.init.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}admin/js/SelectFilter2.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}admin/js/SelectBox.js"></script>
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}admin/css/widgets.css"/>
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}admin/css/base.css"/>
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}admin/css/forms.css"/>
Then render the form as you normally would, but you need to get the fieldset elements and class names right for the css to work. For example:
<fieldset>
<div class="form-row">
<form method="post" action=".">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" value="submit">Add</button>
</form>
</div>
</fieldset>
Then at the BOTTOM of the template (after the markup to render the form), add this script and replace pricetags with whatever your Many to Many (M2M) relationship name is on the model form's model:
<script type="text/javascript">
addEvent(window, "load", function(e) { SelectFilter.init("id_pricetags", "pricetags", 0, "{{ STATIC_URL }}admin/"); });
</script>
Apparently your media location may be something different, but {{ STATIC_URL }}admin/ worked for me.
I got this working very easily in Django 3 in 2020; perhaps things have changed since the question was asked in 2011. All I needed to do was set the widget of the form field, no custom Media defined on the class (django will add it automatically based on the widgets used):
class FooForm(forms.Form):
linked_bars = forms.ModelMultipleChoiceField(queryset=Bar.objects.all(),
widget=widgets.FilteredSelectMultiple(Bar._meta.verbose_name_plural, False))
# end of class, no Media!
You DO need to have the jsi18n loaded globally so in a base template I have:
{% block extrahead %}
{{ block.super }}
<script type="text/javascript" src="/admin/jsi18n/"></script>
{% endblock %}
I am using django 1.6 and python 2.7. I am trying to integrate TinyMCE in django.I have included 'tinymce' in INSTALLED_APPS. Also, I included the tinymce in urls.py. While this works in admin, it doesn't work in templates.
my forms.py is
from django import forms
from .models import Question
from tinymce.widgets import TinyMCE
class QuestionForm(forms.ModelForm):
content = forms.CharField(widget=TinyMCE(attrs={'cols': 80,
'rows': 30}))
class Media:
js = ('/static/js/tiny_mce/tiny_mce.js','',)
class Meta:
model = Question
fields = ('title','content','tags',)
Also, I included the js files in layout.html as follows:
<script type="text/javascript" src="{% static 'js/tiny_mce/tiny_mce.js' %}"></script>
<script type="text/javascript" src="{% static 'js/textareas.js' %}"></script>
the content of textareas.js is:
tinyMCE.init({
mode: "textareas",
theme: "simple"
});
Lastly, my page which uses tinymce is (ask.html) extending layout.html :
{{ form.media }}
{{ form.as_p }}
Any suggestion about where i am going wrong?
I have django project with several apps. In my main html template I am including the relevant resources -- js, css in this case and those entries are coded in by hand like so:
<script src="{% static 'js/test.js' %}"></script>
I'd like to modularize this so that I can somehow loop over my projects and have their dependencies included only if they are installed/enabled. In this way I can also add more apps in the future and not have to touch my main template.
Is there an elegant way to accomplish this?
My thought is that if I can pass each application's required resources to the main template as parameters via views.py then maybe I can loop over them (utilizing sekizai...):
{# Include external app resources #}
{% for app, template in installed_apps.items %}
{% include template %}
{% endfor %}
And views.py would go something like:
external_apps = [foo, bar]
external_apps = settings.EXTERNAL_APPS # Ok, this should exist in settings already
def main(request):
installed_apps = {}
for app in external_apps:
installed_apps[app] = app + "_template.html"
template = loader.get_template('main_template.html')
context = RequestContext(request, {
'installed_apps': installed_apps,
})
return HttpResponse(template.render(context))
Then for each app I would create a template that would fill out the necessary blocks in the main template file.
This approach seems pretty rigid though and I'm wondering if there is a more common or standardized way to go about this.
base.html:
...
<script src="{% static 'js/test.js' %}"></script>
{% block extra_js %}{% endblock extrajs %}
...
In your app template:
{% block extra_js %}<script src="{% static 'js/myapp.js' %}"></script>{% endblock extra_js %}
How do I integrate a calendar widget in my system? I wish to add the calendar widget to my form, which has been designed in Django. I'm attaching a screenshot showing where I want to integrate it. Also, I want the calendar widget to be like http://www.dynarch.com/projects/calendar/.
What file do I need to modify and what code do I need to use?
forms.py
import datetime
from django.forms.extras.widgets import SelectDateWidget
from django.forms import ModelForm, Form
date_field = forms.DateField(widget=SelectDateWidget)
or else there is also a another way using Javascript Using Django time/date widgets in custom form
it may be helpful
I figured it out. You just need to activate the admin interface in settings.py and import AdminDateWidget instead of SelectDateWidget in the forms.py file. Also, insert the following code into the template file of the form. Make sure to put it in between tags. here's the code:
<script type="text/javascript" src="/admin/jsi18n/"></script>
<script type="text/javascript" src="/static/admin/js/core.js"></script>
<script type="text/javascript" src="/static/admin/js/admin/RelatedObjectLookups.js"> </script>
<script type="text/javascript" src="/static/admin/js/jquery.min.js"></script>
<script type="text/javascript" src="/static/admin/js/jquery.init.js"></script>
<script type="text/javascript" src="/static/admin/js/actions.min.js"></script>
<script type="text/javascript" src="/static/admin/js/calendar.js"></script>
<script type="text/javascript" src="/static/admin/js/admin/DateTimeShortcuts.js"></script>
Hope its of use to somebody, cheers!
Saadat
After a long struggle, I managed to get it working for Django 2.0.2. You need the following in the header of template:
<script type="text/javascript" src="/jsi18n/"></script>
<script type="text/javascript" src="{% static 'admin/js/core.js' %}"></script>
<script type="text/javascript" src="{% static 'admin/js/admin/RelatedObjectLookups.js' %}"></script>
<link rel="stylesheet" type="text/css" href="{% static 'admin/css/forms.css' %}"/>
<link rel="stylesheet" type="text/css" href="{% static 'admin/css/base.css' %}"/>
<link rel="stylesheet" type="text/css" href="{% static 'admin/css/widgets.css' %}"/>
urls.py
from django.views.i18n import JavaScriptCatalog
urlpatterns = [
...
path('jsi18n/', JavaScriptCatalog.as_view(), name='javascript-catalog'),
]
And then forms.py
from django import forms
from .models import MyModel
from django.contrib.admin.widgets import AdminDateWidget
class TripDetailForm(forms.ModelForm):
class Meta:
model = MyModel
fields = '__all__'
widgets = {
'my_field': AdminDateWidget(),
}
With this code, you must be good to go.
Just a tip for people who are using Django_filters and they want the admin calendar to show on there date fields (E.x Date is greater than) .. You need to declare the widget in the filter you created .
Like this :
class InterviewFilter(django_filters.FilterSet):
start_date = django_filters.DateFilter(name='date',lookup_expr=('gt'), widget=AdminDateWidget())
end_date = django_filters.DateFilter(name='date',lookup_expr=('lt'), widget=AdminDateWidget())
registry_year = django_filters.DateRangeFilter(field_name='date', lookup_expr='year')
class Meta:
model = Interview
fields = ['position', 'result', 'status']
I have a non-admin form in which I'd like to use filter_horizontal on. I have read this which does much more than what I want (I only want the filter_horizontal). I wanted to check to see if anyone has come up with a simpler (more current) way to just implement the filter_horizontal.
So here is the code:
class County(models.Model):
"""County Names"""
name = models.CharField(max_length=64)
state = USStateField(null=True)
class Company(models.Model):
"""The basics of a company"""
name = models.CharField(max_length = 100)
counties = models.ManyToManyField(County,blank=True, null=True)
Then our form currently look like this. I thought this would work..
from django.contrib.admin.widgets import FilteredSelectMultiple
class RaterCompanyForm(ModelForm):
class Meta:
model = RaterOrganization
exclude = ('remrate_projects',)
widgets = {'counties': FilteredSelectMultiple(verbose_name="Counties",
is_stacked=True,) }
class Media:
css = {'all':['admin/css/widgets.css']}
js = ['/admin/jsi18n/']
BTW: I understand this may be a duplicate of this but his question wasn't answered. I've done plenty of homework here and here but neither of these appear to work.
I know this thread is old, but hopefully this info will help someone else who stumbles upon this page like I did.
After much pain and suffering, I was able to get this to work with Django 1.4. Like rh0dium, I tried all those articles, but had to make a lot of tweaks.
You don't have to do anything special with the ModelForm, but you do have to include all these js and css files in the template:
<script type="text/javascript" src="/admin/jsi18n/"></script>
<script type="text/javascript" src="{{ STATIC_URL }}admin/js/core.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}admin/js/jquery.min.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}admin/js/jquery.init.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}admin/js/SelectFilter2.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}admin/js/SelectBox.js"></script>
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}admin/css/widgets.css"/>
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}admin/css/base.css"/>
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}admin/css/forms.css"/>
Then render the form as you normally would, but you need to get the fieldset elements and class names right for the css to work. For example:
<fieldset>
<div class="form-row">
<form method="post" action=".">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" value="submit">Add</button>
</form>
</div>
</fieldset>
Then at the BOTTOM of the template (after the markup to render the form), add this script and replace pricetags with whatever your Many to Many (M2M) relationship name is on the model form's model:
<script type="text/javascript">
addEvent(window, "load", function(e) { SelectFilter.init("id_pricetags", "pricetags", 0, "{{ STATIC_URL }}admin/"); });
</script>
Apparently your media location may be something different, but {{ STATIC_URL }}admin/ worked for me.
I got this working very easily in Django 3 in 2020; perhaps things have changed since the question was asked in 2011. All I needed to do was set the widget of the form field, no custom Media defined on the class (django will add it automatically based on the widgets used):
class FooForm(forms.Form):
linked_bars = forms.ModelMultipleChoiceField(queryset=Bar.objects.all(),
widget=widgets.FilteredSelectMultiple(Bar._meta.verbose_name_plural, False))
# end of class, no Media!
You DO need to have the jsi18n loaded globally so in a base template I have:
{% block extrahead %}
{{ block.super }}
<script type="text/javascript" src="/admin/jsi18n/"></script>
{% endblock %}