change django-tinymce content css for various object - django

How can I change content_css option in django-tinymce for various objects? I mean that when I use tinymce for model1 then content_css is model1.css and when for model2 then model2.css.
I use

I found out that I can pass extra arguments for tiny_mce in Meta class:
class Meta:
model = MyModel
widgets = {
'field_name': TinyMCE(mce_attrs={'content_css': "style.css"}),
}

Thanks for the szaman's reply, I'll try to describe the process for beginners in new versions of Django (1.9), how to add custom css files to the field named 'text' in the Post model in the Django's admin
Change fields' type in models.py to HTMLField
from tinymce.models import HTMLField
class Post(models.Model):
title = models.TextField(default='')
subtitle = models.TextField(default='')
text = HTMLField(default='')
In the application with the required model, add to admin.py file:
#admin.register(Post) # decorator for adding Django admin for Post
class PostAdmin(admin.ModelAdmin):
form = PostForm # attach custom form
Add form's class
from tinymce.widgets import TinyMCE
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = '__all__' # required in Django (>=1.8)
widgets = {
'text': TinyMCE(mce_attrs={'content_css': ["path_to_css_file",]}),
}

Related

How customize chooser views and add a specific widget to a field using wagtail-generic-chooser

I want to override the basic view in the Article snippet selector, which does not display the checkbox correctly.
class ArticleChooserMixin(ModelChooserMixin):
def get_edit_item_url(self, item):
# for Wagtail 4.x
return reverse(
"wagtailsnippets_app_name_article:edit", args=(quote(item.pk),)
)
class ArticleChooserViewSet(ModelChooserViewSet):
icon = "user"
model = Article
page_title = _("Choose a article")
per_page = 10
order_by = "title"
fields = ["title", "body", "url", "categories", "countries"]
chooser_mixin_class = ArticleChooserMixin
piece of code from the Article model
from dal import autocomplete
...
#register_snippet
class Article(
DraftStateMixin,
RevisionMixin,
index.Indexed,
ClusterableModel,
Orderable,
SourceDataMixin,
):
...
categories = ParentalManyToManyField("app_name.ArticleCategory", blank=True)
countries = ParentalManyToManyField("app_name.Country", blank=True)
...
FieldPanel("categories", widget=autocomplete.ModelSelect2Multiple())
FieldPanel("countries", widget=autocomplete.ModelSelect2Multiple()),
...
Similar problem: https://github.com/wagtail/wagtail-generic-chooser/issues/65
View from the snippet creation how I want it to look and form elements that display the currently selected item
current problem
As per the wagtail-generic-chooser docs - The creation form presented within the chooser is a plain Django ModelForm, which does not make use of the model's panel definition. If you pass a fields attribute on the ViewSet class, it will construct a ModelForm with all of those fields at their default settings. To override this, you can define your own ModelForm class and pass that as form_class:
from django import forms
class ArticleForm(forms.ModelForm):
class Meta:
model = Article
fields = ["title", "body", "url", "categories", "countries"]
widgets = {
"categories": autocomplete.ModelSelect2Multiple(),
"countries": autocomplete.ModelSelect2Multiple(),
}
class ArticleChooserViewSet(ModelChooserViewSet):
# ...
form_class = ArticleForm

Which library is used for importing RadioInput (widgets) in forms.py in Django?

I am using radio buttons for user input in forms.py and want to save the rated value in django database.I have the following fields:
from product.models import Rating
from django.forms import forms
from django.forms.fields import ChoiceField
from django.forms import ModelForm
from django import forms
class RatingForm(forms.ModelForm):
class Meta:
model = Rating
fields = ('product', 'user', 'rating')
widgets = forms.ChoiceField(widget=forms.RadioInput(),
required=True)
Model.py
class Rating(models.Model):
CHOICES = (
('5-stars', '5-stars'),
('4-stars', '4-stars'),
('3-stars', '3-stars'),
('2-stars', '2-stars'),
('1-stars', '1-stars'),
)
product=models.ForeignKey(Product,null=True,blank=True, on_delete=models.PROTECT)
user=models.ForeignKey(User,null=True,blank=True, on_delete=models.PROTECT)
rating=models.ChoiceField(choices=CHOICES, max_length=128)
I didn't find any library for importing this widget. Below is the error i am facing:
AttributeError: module 'django.forms' has no attribute 'RadioInput'?
Please if any one can help? Or suggest any other way to do this?
The widget is called RadioSelect, not RadioWidget. See the documentation.
Note however, you must use the widget directly in the widgets attribute, not as part of a field; and widgets is a dictionary of field names to widgets:
widgets = {'rating': forms.RadioSelect}

How to remove unwanted stuff from ImageField - Django

I want to remove currently and clear field from my django form.
forms.py
class MyUserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ['user_phone','user_dob','user_gender', 'user_image', ]
I am using crispy_forms also
That functionality is provided by ClearableFileInput. If you don't want it, use FileInput instead:
class MyUserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ['user_phone','user_dob','user_gender', 'user_image', ]
widgets = {'user_image': forms.FileInput}

django onchange submit for entire form

I know this has been addressed before but I am having trouble making an on change submit work. Here is my forms.py nothing special in the model or the view. I relize I only selected this for one field but if it worked I would apply it to the others?
#forms.py
from django import forms
from .models import rapidTill
class RapidTillForm(forms.ModelForm):
class Meta:
widgets = {'linkArms': forms.RadioSelect(attrs={'onchange': 'RapidTillForm.submit();'}), 'shank':forms.RadioSelect,
'caddy':forms.RadioSelect, 'liftAssist': forms.RadioSelect, 'folding': forms.RadioSelect}
fields = ['rows', 'space', 'folding', 'shank', 'caddy', 'linkArms', 'liftAssist','shank',]
model = rapidTill
and my form-template.html
{% for field in form %}
<span>{{field.errors}}</span>
<label>{{field.label_tag}}</label>
{{field}}</br>
{%endfor%}
the 'submint' does not require the Model name at the front
class RapidTillForm(forms.ModelForm):
class Meta:
widgets = {'linkArms': forms.RadioSelect(attrs={'onchange': 'submit();'}), 'shank':forms.RadioSelect,
'caddy':forms.RadioSelect, 'liftAssist': forms.RadioSelect, 'folding': forms.RadioSelect}
fields = ['rows', 'space', 'folding', 'shank', 'caddy', 'linkArms', 'liftAssist','shank',]
model = rapidTill

Django admin: How to display a field that is marked as editable=False' in the model?

Even though a field is marked as 'editable=False' in the model, I would like the admin page to display it. Currently it hides the field altogether.. How can this be achieved ?
Use Readonly Fields. Like so (for django >= 1.2):
class MyModelAdmin(admin.ModelAdmin):
readonly_fields=('first',)
Update
This solution is useful if you want to keep the field editable in Admin but non-editable everywhere else. If you want to keep the field non-editable throughout then #Till Backhaus' answer is the better option.
Original Answer
One way to do this would be to use a custom ModelForm in admin. This form can override the required field to make it editable. Thereby you retain editable=False everywhere else but Admin. For e.g. (tested with Django 1.2.3)
# models.py
class FooModel(models.Model):
first = models.CharField(max_length = 255, editable = False)
second = models.CharField(max_length = 255)
def __unicode__(self):
return "{0} {1}".format(self.first, self.second)
# admin.py
class CustomFooForm(forms.ModelForm):
first = forms.CharField()
class Meta:
model = FooModel
fields = ('second',)
class FooAdmin(admin.ModelAdmin):
form = CustomFooForm
admin.site.register(FooModel, FooAdmin)
Add the fields you want to display on your admin page.
Then add the fields you want to be read-only.
Your read-only fields must be in fields as well.
class MyModelAdmin(admin.ModelAdmin):
fields = ['title', 'author', 'published_date', 'updated_date', 'created_date']
readonly_fields = ('updated_date', 'created_date')
You could also set the readonly fields as editable=False in the model (django doc reference for editable here). And then in the Admin overriding the get_readonly_fields method.
# models.py
class MyModel(models.Model):
first = models.CharField(max_length=255, editable=False)
# admin.py
class MyModelAdmin(admin.ModelAdmin):
def get_readonly_fields(self, request, obj=None):
return [f.name for f in obj._meta.fields if not f.editable]
With the above solution I was able to display hidden fields for several objects but got an exception when trying to add a new object.
So I enhanced it like follows:
class HiddenFieldsAdmin(admin.ModelAdmin):
def get_readonly_fields(self, request, obj=None):
try:
return [f.name for f in obj._meta.fields if not f.editable]
except:
# if a new object is to be created the try clause will fail due to missing _meta.fields
return ""
And in the corresponding admin.py file I just had to import the new class and add it whenever registering a new model class
from django.contrib import admin
from .models import Example, HiddenFieldsAdmin
admin.site.register(Example, HiddenFieldsAdmin)
Now I can use it on every class with non-editable fields and so far I saw no unwanted side effects.
You can try this
#admin.register(AgentLinks)
class AgentLinksAdmin(admin.ModelAdmin):
readonly_fields = ('link', )