I am trying to develop a ckeditor comment box in Django. I successfully added the comment box. But now I am facing the issue in editing the comment part. What I am trying to do is when the user click on the edit button near to the comment, a modal popup appears and editing should happens there. The issue is the ckeditor is not showing in the modal. Instead of ckeditor a normal text field with data from the database is showing. In the console it showing "editor-element-conflict" error. Is there any solution for this?
I've figured out!
It happens because you have a few ckeditor fields on the page, and they have the same ID, and CKEditor gets confused because it finds a few elements with the same ID.
Solution: change IDs dynamically when the page is being generated.
I don't know the structure of your model, but I can assume that your form is defined like this:
class Comment(models.Model):
text = models.TextField()
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = “__all__”
Then you need to change it like this:
from ckeditor.widgets import CKEditorWidget
class CommentForm(forms.ModelForm):
base_textarea_id = "id_text"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.textarea_id_counter = 0
self.fields['text'].widget = CKEditorWidget(attrs={'id': self.get_textarea_next_id})
def get_textarea_next_id(self):
result = self.base_textarea_id + str(self.textarea_id_counter)
self.textarea_id_counter += 1
return result
class Meta:
model = Comment
fields = “__all__”
Of course, it’s based on very simplified model example, but I hope you’ve got the point.
Related
Very similar to this question, but I tried the accepted answer and it did not work. Here's what's going on.
I have a form for tagging people in photos that looks like this:
forms.py
class TaggingForm(forms.Form):
def __init__(self, *args, **kwargs):
queryset = kwargs.pop('queryset')
super(TaggingForm, self).__init__(*args, **kwargs)
self.fields['people'] = forms.ModelMultipleChoiceField(required=False, queryset=queryset, widget=forms.CheckboxSelectMultiple)
...
models.py
class Photo(models.Model):
user = models.ForeignKey(User)
...
class Person(models.Model):
user = models.ForeignKey(User)
photos = models.ManyToManyField(Photo)
...
I want users to be able to edit the tags on their photos after they initially tag them, so I have a page where they can go to view a single photo and edit its tags. For obvious reasons I want to have the already-tagged individuals' checkboxes pre-selected. I tried to do this by giving the form's initial dictionary a list of people I wanted selected, as in the answer to the question I linked above.
views.py
def photo_detail(request,photo_id):
photo = Photo.objects.get(id=photo_id)
initial = {'photo_id':photo.id, 'people':[p for p in photo.person_set.all()]}
form_queryset = Person.objects.filter(user=request.user)
if request.method == "POST":
form = TaggingForm(request.POST, queryset=form_queryset)
# do stuff
else:
form = TaggingForm(initial=initial, queryset=form_queryset)
...
When I try to initialize people as in the above code, the form doesn't show up, but no errors are thrown either. If I take the 'people' key/value pair out of the initial dictionary the form shows up fine, but without any people checked.
Also I'm using Django 1.5 if that matters. Thanks in advance.
What you could do is simply use django forms to handle all of this for you. Please refer to this question. Ideally it boils down to lettings djnago handle your forms and its validation and initial values.
Now this is actually a really good practice to get used to since, you're dissecting all your logic and your presentation. Its a great DRY principle.
Django raw_id_fields don't display tables the way I expect, am I doing something wrong? I'm trying to use a raw_id_fields widget to edit a ForeignKey field as follows:
#models.py
class OrderLine(models.Model):
product = ForeignKey('SternProduct')
class SternProduct(models.Model):
def __unicode__(self): return self.product_num
product_num = models.CharField(max_length=255)
#admin.py
#import and register stuff
class OrderLineAdmin(admin.ModelAdmin):
raw_id_fields=('product')
I get the little textbox and magnifier widget as expected, but clicking the magnifier gives me this:
flickr.com/photos/28928816#N00/5244376512/sizes/o/in/photostream/
(sorry, can't post more than one hyperlink apparently)
I thought I would get something closer to the changelist page c/w columns, filters and search fields. In fact, that's apparently what others get.
Any thoughts about how to enable the more featureful widget?
Ah, OK, this should have been obvious, but it isn't explained in the Django docs. The list that appears in the raw_id_fields popup uses the same options as the admin object for the referenced model. So in my example, to get a nice looking popup I needed to create a SternProductAdmin object as follows:
class SternProductAdmin(admin.ModelAdmin):
list_display = ('__unicode__', 'drawing_number', 'drawing_revision',)
list_filter = ('drawing_number',)
search_fields = ('drawing_number',)
actions = None
Hopefully this will help others in the future.
If a django model contains a foreign key field, and if that field is shown in list mode, then it shows up as text, instead of displaying a link to the foreign object.
Is it possible to automatically display all foreign keys as links instead of flat text?
(of course it is possible to do that on a field by field basis, but is there a general method?)
Example:
class Author(models.Model):
...
class Post(models.Model):
author = models.ForeignKey(Author)
Now I choose a ModelAdmin such that the author shows up in list mode:
class PostAdmin(admin.ModelAdmin):
list_display = [..., 'author',...]
Now in list mode, the author field will just use the __unicode__ method of the Author class to display the author. On the top of that I would like a link pointing to the url of the corresponding author in the admin site. Is that possible?
Manual method:
For the sake of completeness, I add the manual method. It would be to add a method author_link in the PostAdmin class:
def author_link(self, item):
return '%s' % (item.id, unicode(item))
author_link.allow_tags = True
That will work for that particular field but that is not what I want. I want a general method to achieve the same effect. (One of the problems is how to figure out automatically the path to an object in the django admin site.)
I was looking for a solution to the same problem and ran across this question... ended up solving it myself. The OP might not be interested anymore but this could still be useful to someone.
from functools import partial
from django.forms import MediaDefiningClass
class ModelAdminWithForeignKeyLinksMetaclass(MediaDefiningClass):
def __getattr__(cls, name):
def foreign_key_link(instance, field):
target = getattr(instance, field)
return u'%s' % (
target._meta.app_label, target._meta.module_name, target.id, unicode(target))
if name[:8] == 'link_to_':
method = partial(foreign_key_link, field=name[8:])
method.__name__ = name[8:]
method.allow_tags = True
setattr(cls, name, method)
return getattr(cls, name)
raise AttributeError
class Book(models.Model):
title = models.CharField()
author = models.ForeignKey(Author)
class BookAdmin(admin.ModelAdmin):
__metaclass__ = ModelAdminWithForeignKeyLinksMetaclass
list_display = ('title', 'link_to_author')
Replace 'partial' with Django's 'curry' if not using python >= 2.5.
I don't think there is a mechanism to do what you want automatically out of the box.
But as far as determining the path to an admin edit page based on the id of an object, all you need are two pieces of information:
a) self.model._meta.app_label
b) self.model._meta.module_name
Then, for instance, to go to the edit page for that model you would do:
'../%s_%s_change/%d' % (self.model._meta.app_label, self.model._meta.module_name, item.id)
Take a look at django.contrib.admin.options.ModelAdmin.get_urls to see how they do it.
I suppose you could have a callable that takes a model name and an id, creates a model of the specified type just to get the label and name (no need to hit the database) and generates the URL a above.
But are you sure you can't get by using inlines? It would make for a better user interface to have all the related components in one page...
Edit:
Inlines (linked to docs) allow an admin interface to display a parent-child relationship in one page instead of breaking it into two.
In the Post/Author example you provided, using inlines would mean that the page for editing Posts would also display an inline form for adding/editing/removing Authors. Much more natural to the end user.
What you can do in your admin list view is create a callable in the Post model that will render a comma separated list of Authors. So you will have your Post list view showing the proper Authors, and you edit the Authors associated to a Post directly in the Post admin interface.
See https://docs.djangoproject.com/en/stable/ref/contrib/admin/#admin-reverse-urls
Example:
from django.utils.html import format_html
def get_admin_change_link(app_label, model_name, obj_id, name):
url = reverse('admin:%s_%s_change' % (app_label, model_name),
args=(obj_id,))
return format_html('%s' % (
url, unicode(name)
))
I'm developing a portfolio application. Within this application, I have a model called "Project" which looks something like this:
class Project(models.Model):
...
images = models.ManyToManyField(Image)
...
so, basically, this Project can contain a set of images (any of these images may belong to another Project as well).
Now, what I'd like to add is a way of specifying that one of these "images" is a "lead_image".
So I could add something like this:
class Project(models.Model):
...
images = models.ManyToManyField(Image, related_name='images')
lead_image = models.ForeignKey(Image, related_name='lead_image')
...
However, the problem with this is that in this case, lead_image can be ANY image. What I really want is for it to be one of the "images" that belongs to to this model instance.
I'm thinking that I need to use "ForeignKey.limit_choices_to" argument, but I'm unsure of how to use this...especially since when the model instance is first created, there won't yet be any images in the "images" directory.
Any help would be greatly appeciated.
Doug
If you're wanting to achieve the limiting effect in the admin tool, you can override the formfield-for-foreignkey method and insert your own filter.
class ProjectAdmin(admin.ModelAdmin):
# ...
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == "lead_image":
kwargs["queryset"] = self.model.images.all()
return db_field.formfield(**kwargs)
return super(ProjectAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
The problem I see here (with this general idea of only picking from picked images) is that for new models, initially model.images won't be set when the page loads. You'll probably face this problem no matter what server-side trick you go with.
It could work, but it requires an extra click: When the model is first created the ManyToMany model.images will be picked. After picked, if "Save and Continue" is clicked, then those images should appear in the model.lead-image FK field.
Your other option would be to override the default admin form and create something custom (custom as in custom fancy-pants javascript to auto-update the 'lead image' field combo box).
Another approach to your problem is to use a intermediate table with a boolean property 'is_lead_image'.
class Image(models.Model):
...
class Project(models.Model):
images = models.ManyToManyField(Image, through='ProjectImage')
...
class ProjectImage(models.Model):
image = models.ForeignKey(Image)
project = models.ForeignKey(Project)
is_lead_image = models.Boolean(default=False)
def save(self, *args, **kwargs):
if self.is_lead_image:
self._default_manager.filter(project=self.project).update(is_lead_image=False)
return super(ProjectImage, self).save(*args, **kwargs)
*Note: If you like and if you have access you can also just add the is_lead_image field and the save directly to the Image class.
A have 3 models: Project, Image and Video with ManyToManyField relation:
class Project(models.Model):
images = models.ManyToManyField('Image', through='Project_Images')
video = models.ManyToManyField('Video', through='Project_Video')
class Image(models.Model):
original = models.ImageField()
projects = models.ManyToManyField('Project', through='Project_Images')
class Video(models.Model):
projects = models.ManyToManyField('Project', through='Project_Video')
I configure project's admin form with inline forms of Images and Videos linked to current project:
class ProjectAdmin(admin.ModelAdmin):
inlines = [VideoInline, ImagesInline]
class ImagesInline(admin.TabularInline):
model = Project_Images
raw_id_fields = ['project','image']
class VideoInline(admin.TabularInline):
model = Project_Video
raw_id_fields = ['project','video']
But inline table with simple select field and delete checkbox is much miserable for me, and I want to show here previews of images or video (youtube). I solve this for images with help of AdminImageWidget:
class ImageForm(forms.ModelForm):
class Meta:
model = Image
preview = forms.ImageField(widget=AdminImageWidget())
def __init__(self, *args, **kwargs):
super(ImageForm, self).__init__(*args, **kwargs)
try:
image = Image.objects.get(id=self.instance.image_id)
self.fields["preview"].initial = image.original
except:
pass
class ImagesInline(admin.TabularInline):
.....
form = ImageForm
Is it best way to do this? In my case I don't need file upload input, only image-preview in inline form table. I need also preview for youtube video, should I write my own widget for displaying video and apply it to some fake field ?
It's strange to solve this issue by widget for unnecessary fake field. Or is it normal way?
Any help will be very much appreciated!
Thanks!
You should create a widget similar to AdminImageWidget but that displays only the image, not the upload box. To apply that widget you don't need a custom Form class or a fake field, just use formfield_overrides on your ImageInline:
class ImageInline(admin.TabularInline):
...
formfield_overrides = { models.ImageField: {'widget': YourPreviewWidget}}
EDIT: Oops, didn't fully process the ManyToManyField issue - you're displaying inlines for the "through" table, not the table with the actual ImageFields. Given that, what you're doing now may be not such a bad solution. The alternative I can think of would be to write a specialized replacement widget for the Select, that knows how to display both the select box and a preview image for the currently selected Image object. That way you could avoid the need for the fake extra field.