I am trying to intregrate django-summernote in my blog post admin area.
when I set summernote_fields = ('description',) and register to admin area, I am getting error like below :
for model in model_or_iterable:
TypeError: 'MediaDefiningClass' object is not iterable
My admin.py is given below :
from django.contrib import admin
from django_summernote.admin import SummernoteModelAdmin
from .models import Blog
class BlogPostSummerNote(SummernoteModelAdmin):
summernote_fields = ('description',)
#admin.register(Blog)
class BlogAdmin(admin.ModelAdmin):
list_display = ('title','slug','author','publish','status')
prepopulated_fields = {'slug':('title',)}
admin.site.register(BlogPostSummerNote)
I can't able to figure this out . Can any one tell me why this is happening ??
############# SOLUTION #################
I Solved this problem by doing as below in admin.py:
from django.contrib import admin
from django_summernote.admin import SummernoteModelAdmin
from .models import Blog
#admin.register(Blog)
class BlogPostSummerNote(SummernoteModelAdmin):
list_display = ('title','slug','author','publish','status')
summernote_fields = ('description',)
prepopulated_fields = {'slug':('title',)}
I am trying to build a Django (version 3.05) REST API call that will render to a chosen HTML template.
I am, however, receiving a number of errors that I haven't found a solution to on StackOverflow (And yes, I've looked far and wide).
Since my errors are many and varying depending on what I attempt, let me rather ask how to do it correctly to begin with.
In my view set up (below), what do I need to add (or change) in order to render the queryset to an HTML template?
models.py:
from django.db import models
class Hero(models.Model):
name = models.CharField(max_length=60)
alias = models.CharField(max_length=60)
def __str__(self):
return self.name
serializers.py:
from rest_framework import serializers
from .models import Hero
class HeroSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Hero
fields = ('name', 'alias')
views.py:
from rest_framework import viewsets
from .serializers import HeroSerializer
from .models import Hero
class HeroViewSet(viewsets.ModelViewSet):
queryset = Hero.objects.all().order_by('name')
serializer_class = HeroSerializer
# over here - how do I render the queryset /to/my/template.html
myapi/urls.py:
from django.urls import include, path
from rest_framework import routers
from . import views
router = routers.DefaultRouter()
router.register(r'heroes', views.HeroViewSet)
you should change your view from ModelViewSet to APIView.
with API view you can include renderer_classes and template_name.
check here for more information
I am building a Portfolio web app with Django.
I am unable to save an image into my database in my web app.
Also, to replace an existing image in the database does not work.
Note: I don't get any error message from Django. The web app will tell me no file being added.
On the Django Admin section(Django site administration page "localhost:8000/admin" I am able to add a new image and change an existing one.
How can I enable this functionality without going to django admin section.
Here's my code
views.py:
from django.views.generic.edit import CreateView, UpdateView
from django.urls import reverse_lazy
from .models import Jobs
class JobsCreateView(CreateView):
model = Jobs
fields = ['image']
template_name = "new_job.html"
class JobsUpdateView(UpdateView):
model = Jobs
fields = ['image']
template_name = "change_job.html"
success_url = reverse_lazy('home')
models.py:
from django.db import models
from django.urls import reverse
class Jobs(models.Model):
image = models.ImageField(upload_to="images/")
upload_date = models.DateTimeField(auto_now_add=True)
def get_absolute_url(self):
return reverse('home', args=[str(self.id)])
If you need any additional information from me, please let me know or you can see the complete code of this project here
I have an app named doors and my models.py for the app has 10 tables/class. Under my admin.py, how do I register every model in the file models.py?
For example, currently I have to hardcode it:
from django.contrib import admin
from doors.models import *
admin.site.register(Group)
admin.site.register(Item)
admin.site.register(ItemType)
admin.site.register(Location)
admin.site.register(Log)
admin.site.register(Order)
admin.site.register(Property)
admin.site.register(User)
admin.site.register(Vendor)
Is there a way I perhaps find every class in models.py and loop through and register each class? Or is there some kind of wildcard I can use with Django?
Seems get_models and get_app are no longer available in django 1.8.
The following can be used:
from django.contrib import admin
from django.apps import apps
app = apps.get_app_config('dashboard')
for model_name, model in app.models.items():
admin.site.register(model)
EXTENSION: If you would like to show all or select fields of the model as a grid instead of a single column unicode representation of the model objects you may use this:
app = apps.get_app_config('your_app_name')
for model_name, model in app.models.items():
model_admin = type(model_name + "Admin", (admin.ModelAdmin,), {})
model_admin.list_display = model.admin_list_display if hasattr(model, 'admin_list_display') else tuple([field.name for field in model._meta.fields])
model_admin.list_filter = model.admin_list_filter if hasattr(model, 'admin_list_filter') else model_admin.list_display
model_admin.list_display_links = model.admin_list_display_links if hasattr(model, 'admin_list_display_links') else ()
model_admin.list_editable = model.admin_list_editable if hasattr(model, 'admin_list_editable') else ()
model_admin.search_fields = model.admin_search_fields if hasattr(model, 'admin_search_fields') else ()
admin.site.register(model, model_admin)
What this does is, it extends ModelAdmin class on the fly and sets the list_display field which is required for showing model data in grid representation in the admin. If you list your desired fields in your model as admin_list_display it takes that one, or generates a tuple of all fields available in the model, otherwise.
Other optional fields can similarly be set, such as list_filter.
See django documentation for more info on list_display.
I figured it out with #arie's link (for django < 1.8):
from django.contrib import admin
from django.db.models import get_models, get_app
for model in get_models(get_app('doors')):
admin.site.register(model)
But I wonder if I can do this without get_app... Couldn't the code be smart enough to know the name of its own app?
From Django 1.7 on, you can use this code in your admin.py:
from django.apps import apps
from django.contrib import admin
from django.contrib.admin.sites import AlreadyRegistered
app_models = apps.get_app_config('my_app').get_models()
for model in app_models:
try:
admin.site.register(model)
except AlreadyRegistered:
pass
From Django 1.8, to fix the error message
RemovedInDjango19Warning: django.db.models.get_app is deprecated.
We can use this approach in 2 lines
from django.contrib import admin
from my_app.models import *
from django.apps import apps
for model in apps.get_app_config('my_app').models.values():
admin.site.register(model)
from django.apps import apps
from django.contrib.admin.sites import AlreadyRegistered
app_models = apps.get_app_config('app-name').get_models()
for model in app_models:
try:
admin.site.register(model)
except AlreadyRegistered:
pass
from django.contrib import admin
from .models import Projects, ProjectsUsers, Comments, ProjectsDescription
Models = (Projects, ProjectsUsers, Comments, ProjectsDescription)
admin.site.register(Models)
From Django3.0,you can try add the following code in admin.py
from . import models
class ListAdminMixin(object):
def __init__(self, model, admin_site):
self.list_display = [field.name for field in model._meta.fields if field.name != "id"]
super(ListAdminMixin, self).__init__(model, admin_site)
for m in [your_model_name]:
mod = getattr(models, m)
admin_class = type('AdminClass', (ListAdminMixin, admin.ModelAdmin), {})
try:
admin.site.register(mod, admin_class)
except admin.sites.AlreadyRegistered:
pass
I am working thru the Practical Django Projects book and am stumped. The book is for an earlier version of Django. I am using v1.3.
The problem is in the view, at 'search_keyword_keyword__in...'
from django.contrib.flatpages.models import FlatPage
from django.shortcuts import render_to_response
def search(request):
query = request.GET.get('q', '')
keyword_results = results = []
if query:
keyword_results = FlatPage.objects.filter(searchkeyword__keyword__in=query.split()).distinct()
results = FlatPage.objects.filter(content__icontains=query)
return render_to_response('search/search.html',
{'query' : query,
'keyword_results': keyword_results,
'results' : results })
The models.py is
from django.contrib.flatpages.models import FlatPage
from django.db import models
class SearchKeyword(models.Model):
keyword = models.CharField(max_length=50)
page = models.ForeignKey(FlatPage)
def __unicode__(self):
return self.keyword
The full error is:
Cannot resolve keyword 'searchkeyword' into field. Choices are: content, enable_comments, id, registration_required, sites, template_name, title, url
Which I think are the options for FlatPages. It doesn't seem like the foreign key relationship is being found.
Any ideas what could be wrong or how to correctly do the lookup? Thanks.
Here is the admin.py in case it has some bearing:
from django.contrib.flatpages.admin import FlatPageAdmin
from django.contrib import admin
from cms.search.models import SearchKeyword
from django.contrib.flatpages.models import FlatPage
# Define an inline admin descriptor for SearchKeywords model
class SearchKeywordInline(admin.TabularInline):
model = SearchKeyword
# Define a FlatPageAdmin class
class ExtendedFlatPageAdmin(FlatPageAdmin):
inlines = [
SearchKeywordInline,
]
# Re-register FlatPageAdmin
admin.site.unregister(FlatPage)
admin.site.register(FlatPage, ExtendedFlatPageAdmin)
The reverse relationship for your ForeignKey would be named searchkeyword_set (see https://docs.djangoproject.com/en/dev/topics/db/queries/#backwards-related-objects), so your queryset should have searchkeyword_set__keyword__in as a a parameter (or you can use related_name.
If that didn't work, you should check that you have done manage.py syncdb ?
It seems the problem was:
from django.contrib.flatpages.models import FlatPage
from django.db import models
The models needs to come first, like:
from django.db import models
from django.contrib.flatpages.models import FlatPage
I think what was happening is the FlatPage instance was being created before the ForeignKey was created, therefore the SearchKeyword attribute was not available to FlatPage.