I'm trying to duplicate the example in 2.4 in the Django-CMS docs (http://docs.django-cms.org/en/2.3.5/extending_cms/custom_plugins.html). However, whenever I specify the model in cms_plugins.py under class HelloPlugin, the entire CMS section in the admin disappears. Any idea what's causing this?
models.py
from django.db import models
class MyModel(models.Model):
title = models.CharField(max_length=50, null=True, blank=True)
def __unicode__(self):
return self.title
from cms.models.pluginmodel import CMSPlugin
class HelloPlugin(CMSPlugin):
ad = models.ForeignKey('core.MyModel', related_name='plugins')
def __unicode__(self):
return self.ad.title
cms_plugins.py
class HelloPlugin(CMSPluginBase):
model = MyModel
name = _("MyModel Plugin")
render_template = "myplugin.html"
def render(self, context, instance, placeholder):
context['instance'] = instance
return context
plugin_pool.register_plugin(HelloPlugin)
Small, but significant mistake. I was importing the model, and not the plugin.
Related
i want to create a tag field like youtube give tage field while uploading a vedio this is what i tried in in my blog form
my models.py
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
# Create your models here.
class Blog(models.Model):
author = models.OneToOneField(User, on_delete=models.CASCADE,)
title = models.CharField(max_length=200,blank=False,)
thumbnail = models.ImageField(upload_to='blogs_thumbnail',default='blogdefa.png')
tags = models.CharField(max_length=500, blank=False, default='Blog')
data = models.TextField(blank=False,)
published_date = models.DateTimeField(default=timezone.now,editable=False)
update_at = models.DateTimeField(auto_now=True,editable=False)
def __str__(self):
return self.title
any idea how to do it i don,t know how to do it
my forms.py
from django import forms
from django.forms import ModelForm, Textarea
from django.contrib.auth.models import User
from .models import Blog, comment, report
forms here
class BlogForm(forms.ModelForm):
class Meta:
model = Blog
fields = '__all__'
widgets = {'data': Textarea(attrs={'cols': 80, 'rows': 20, 'placeholder':'Write Here'}),
'title':forms.TextInput(attrs={'placeholder':'Your Blog Title Here'}),
'tags': forms.TextInput(attrs={'placeholder':'Please enter you content related tags'}),
}
exclude = ['author','published_date','update_at']
all i want is user can create his own tag for blogs like in youtube and not like stackoverflow where you have use to choose you tag
please help
currently it look like this
which is not cool
First thing is that tags work. So to get them working you should relate it to your post.
So you should create a Tag model and use a ManytoManyRelated field to relate tags because you need to get to the post/result at the end using tags.
from django.db import models
from django_extensions.db.fields import AutoSlugField
from django.db.models import CharField, TextField, DateField, EmailField, ManyToManyField
class Tag(models.Model):
name = CharField(max_length=31, unique=True, default="tag-django")
slug = AutoSlugField(max_length=31, unique=True, populate_from=["name"])
def __str__(self):
return self.name
class YourPost(models.Model):
name = CharField(max_length=31, db_index=True)
slug = AutoSlugField(max_length=31, unique=True, populate_from=["name"])
description = TextField()
date_founded = DateField(auto_now_add=True)
contact = EmailField()
tags = ManyToManyField(Tag, related_name="tags")
class Meta:
get_latest_by = ["date_founded"]
def __str__(self):
return self.name
Go on from here.
Create serializers, Viewsets. Relate your tags to your post.
I am using Django 1.8.8.
I have a lot of models defined as such:
class MainModel(models.Model):
value = models.IntegerField(null=False, editable=True, default=20)
dt_modified = models.DateTimeField(null=True, auto_now=True)
class MyModel1(MainModel, models.Model):
name = models.CharField(null=False, editable=False, max_length=50)
class MyModel2(MainModel, models.Model):
foo = models.CharField(null=False, editable=False, max_length=50)
My admin page is currently setup as such,
class MyModelAdmin(admin.ModelAdmin):
list_display = ('value', 'dt_modified')
search_fields = ['value']
date_hierarchy = 'dt_modified'
models = [MyModel1, MyModel2]
admin.site.register(models, MyModelAdmin)
I want to setup my admin page as follows:
Have one link on the top page/admin, "MainModels" which directs me to another page where I can select from a list of all derived models of MyModel, i.e. [MyModel1, MyModel2, ....MyMoneyN] which lets me edit the selected derived model. MyModel#.
The problem with the code above is it creates a top level link for each numbered model.
You're really best off using something like Grapelli or another custom admin replacement. You can set custom pages with different sets of models, adjust hidden / shown by default, etc. Trying to do this with vanilla admin is going to be problematic.
Here is an example of something close to what you want to do with grappelli
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from grappelli.dashboard import modules, Dashboard
class MyDashboard(Dashboard):
def __init__(self, **kwargs):
Dashboard.__init__(self, **kwargs)
# append an app list module for "Applications"
self.children.append(modules.AppList(
title=_('Applications'),
column=1,
css_classes=('grp-collapse grp-closed',),
collapsible=True,
exclude=('django.contrib.*',),
))
You need your own changelist to do this:
class MyChangeList(ChangeList):
def url_for_result(self, result):
link = your_function_to_create_link()
return link
Then use your Changelist in ModelAdmin:
class MyModelAdmin(admin.ModelAdmin):
def get_changelist(self, request, **kwargs):
return MyChangeList
i am new to django-rest-framework,i am unble to get the image as browse button in my rest framework,i am getting text field,here is my code as follows...........
views.py
from django.shortcuts import render
from serializers import *
from rest_framework import viewsets
class newsViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = news.objects.all()
serializer_class = newsSerializer
class news_categoriesViewSet(viewsets.ModelViewSet):
queryset = news_categories.objects.all()
serializer_class = news_categoriesSerializer
models.py
from django.db import models
from django.utils.encoding import smart_unicode
class news_categories(models.Model):
cat_name = models.CharField(max_length=30, null=True)
created_at = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return smart_unicode(self.cat_name)
def Content_files(instance, filename):
return '/'.join(['Media','News Image', filename])
class news(models.Model):
name = models.CharField(max_length=30,null=True)
description = models.TextField()
cat_id = models.ForeignKey('news_categories')
image = models.FileField(upload_to=Content_files,null=True)
date = models.DateField()
created_at = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return smart_unicode(self.name)
serializers.py
from django.forms import widgets
from rest_framework import serializers
from models import *
class newsSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = news
fields = ('url','id','name','description','cat_id','image','date')
class news_categoriesSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = news_categories
fields = ('url','id','cat_name')
Any one can Help me?Thanks in Advance....
the problem with settings.py and version of rest framework ,use 2.4.4
I stumbled upon the same problem when I updated to version 3.0. The solution is to define the FileField or ImageField in your serializer using a style attribute:
file = serializers.FileField(style = {'input_type': 'file'})
i have two models
class Reporter(models.Model):
full_name = models.CharField(max_length=70)
# On Python 3: def __str__(self):
def __unicode__(self):
return self.full_name
class Article(models.Model):
pub_date = models.DateField()
headline = models.CharField(max_length=200)
content = models.TextField()
reporter = models.ForeignKey(Reporter)
now in the admin site i want to register the reporter's model and then when it is clicked the Article model objects can be added from within that reporter's model .. is it possible ?? if yes how to accomplish this ??
You need inline model admin. In your admin.py, add the following:
from django.contrib import admin
from .models import Article, Reporter
class ArticleInline(admin.TabularInline):
model = Article
class ReporterAdmin(admin.ModelAdmin):
inlines = [
ArticleInline,
]
admin.site.register(Reporter, ReporterAdmin)
I need to filter database by default every time that I see it (when I save changes or when I open database first time).
Can anybody tell me how to do it?
This is possible with custom custom Managers:
Say you have a class called Book:
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=50)
And you want the admin pages for book objects to only show books by Roald Dahl, then you can add a custom manager:
class DahlBookManager(models.Manager):
def get_query_set(self):
return super(DahlBookManager, self).get_query_set().filter(author='Roald Dahl')
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=50)
objects = models.Manager()
dahl_objects = DahlBookManager()
Then you just need to specify that your ModelAdmin should use the dahl_objects manager, which is explained here.
Here is my models.py:
from django.db import models
class DahlBookManager(models.Manager):
def get_query_set(self):
return super(DahlBookManager, self).get_query_set().filter(processed=False)
class Book(models.Model):
book_name = models.CharField('book',max_length=1000,null=True, blank=True)
url = models.CharField(max_length=1000,null=True, blank=True)
processed = models.BooleanField('Done',)
def __str__(self):
return u'%s' % (self.book_name)
def url1(self):
return '%s' % (self._url, self.url)
site_url1.allow_tags = True
class Admin:
pass
class Meta:
db_table = 'books'
objects = models.Manager()
dahl_objects = DahlBookManager()
here is my admin.py:
from django.contrib import admin
from mybooks.booksdb.models import Book
from django import forms
admin.autodiscover()
class BookAdmin(admin.ModelAdmin):
def queryset(self,request):
qs=self.model.objects.get_query_set()
ordering = self.ordering or ()
if ordering:
qs=qs.order_by(*ordering)
return qs
....
No filter by default. Where is my miss?