I want to add a default value and have it populate the field in a Wagtail template based on a Django model. I know I am returning the value because if I populate 'help-text' attribute with this value, it works but I cannot get it populate the field with the default attribute. I am using a field panel for the content panel. This Class is very long so I did not post the whole thing.
def live_video_url():
return constants.streaming_info['live-video-captions']
class MeetingPage(Page):
live_video_url = models.URLField(
default=live_video_url,
blank=False,
help_text=live_video_url,
null=True
)
content_panels = [
FieldPanel('live_video_url'),
]
I am getting this in the actual field in the Wagtail editor, but the correct url string in help-text:
<django.db.models.query_utils.DeferredAttribute object at 0x104547470>
Example of adding a default value in a field in the wagtail admin
# models.py
from django.db import models
from wagtail.core.models import Page
from wagtail.admin.edit_handlers import FieldPanel
from wagtail.admin.forms import WagtailAdminPageForm
class MyItemForm(WagtailAdminPageForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
description = self.fields["description"]
description.widget.attrs["value"] = "My new initial data"
class MyItem(Page):
description = models.CharField(max_length=255, default='', blank=True)
content_panels = Page.content_panels + [
FieldPanel("description"),
]
base_form_class = MyItemForm
Related
I made a class in home/models.py to create page and add to specific site in wagtail cms admin interface depending on site id same as documentation https://docs.djangoproject.com/en/2.1/ref/contrib/sites/
also I'm inheriting MenuPage inside the class to use sub menu
but when I made migration I got error of page inherit even if I change the inheritance.
help please?
from django.db import models
from django.contrib.sites.models import Site
from django.contrib.sites.managers import CurrentSiteManager
from django.utils import translation
# New imports added for ParentalKey, Orderable, InlinePanel, ImageChooserPanel
from modelcluster.fields import ParentalKey
from wagtail.core.models import Page, PageManager, Orderable
from wagtail.core.fields import RichTextField
from wagtail.admin.edit_handlers import FieldPanel, MultiFieldPanel, InlinePanel
from wagtail.images.edit_handlers import ImageChooserPanel
from wagtail.search import index
from wagtailmenus.models import MenuPage
from wagtailmenus.panels import menupage_panel
class TranslatedField():
def __init__(self, en_field, sv_field):
self.en_field = en_field
self.sv_field = sv_field
def __get__(self, instance, owner):
if translation.get_language() == 'sv':
return getattr(instance, self.sv_field)
else:
return getattr(instance, self.en_field)
class HomePage(MenuPage):
body = RichTextField(blank=True)
site = models.ForeignKey(Site, on_delete=models.CASCADE)
objects = models.Manager()
on_site = CurrentSiteManager()
content_panels = MenuPage.content_panels + [
FieldPanel('body', classname="full"),
FieldPanel('site'),
]
class HomeOnePage(MenuPage):
body = RichTextField(blank=True)
site = models.ForeignKey(Site, on_delete=models.CASCADE)
objects = models.Manager()
on_site = CurrentSiteManager()
content_panels = MenuPage.content_panels + [
FieldPanel('body', classname="full"),
FieldPanel('site'),
]
class BlogIndexPage(MenuPage):
intro = RichTextField(blank=True)
site = models.ForeignKey(Site, on_delete=models.CASCADE)
objects = models.Manager()
on_site = CurrentSiteManager()
content_panels = MenuPage.content_panels + [
FieldPanel('intro', classname="full"),
FieldPanel('site'),
]
class BlogPage(MenuPage):
date = models.DateField("Post date")
intro = models.CharField(max_length=250)
body = RichTextField(blank=True)
site = models.ForeignKey(Site, on_delete=models.CASCADE)
objects = models.Manager()
on_site = CurrentSiteManager()
#translated_title = TranslatedField(
# 'title',
# 'title_sv',
#)
#body = TranslatedField(
# 'body_en',
# 'body_sv',
#)
search_fields = MenuPage.search_fields + [
index.SearchField('intro'),
index.SearchField('body'),
]
content_panels = MenuPage.content_panels + [
FieldPanel('date'),
FieldPanel('intro'),
FieldPanel('body', classname="full"),
FieldPanel('site'),
InlinePanel('gallery_images', label="Gallery images", help_text = "add photo to your site"),
]
class BlogPageGalleryImage(Orderable):
page = ParentalKey(BlogPage, on_delete=models.CASCADE, related_name='gallery_images')
image = models.ForeignKey(
'wagtailimages.Image', on_delete=models.CASCADE, related_name='+'
)
caption = models.CharField(blank=True, max_length=250)
panels = [
ImageChooserPanel('image'),
FieldPanel('caption'),
]
SystemCheckError: System check identified some issues:
ERRORS:
home.BlogIndexPage: (wagtailcore.E002) Manager does not inherit from PageManager
HINT: Ensure that custom Page managers inherit from wagtail.core.models.PageManager
home.BlogPage: (wagtailcore.E002) Manager does not inherit from PageManager
HINT: Ensure that custom Page managers inherit from wagtail.core.models.PageManager
home.HomeOnePage: (wagtailcore.E002) Manager does not inherit from PageManager
HINT: Ensure that custom Page managers inherit from wagtail.core.models.PageManager
home.HomePage: (wagtailcore.E002) Manager does not inherit from PageManager
HINT: Ensure that custom Page managers inherit from wagtail.core.models.PageManager
WARNINGS:
home.BlogIndexPage.site: (wagtailcore.W001) Field hasn't specified on_delete action
HINT: Set on_delete=models.SET_NULL and make sure the field is nullable or set on_delete=models.PROTECT. Wagtail does not allow simple database CASCADE because it will corrupt its tree storage.
home.BlogPage.site: (wagtailcore.W001) Field hasn't specified on_delete action
HINT: Set on_delete=models.SET_NULL and make sure the field is nullable or set on_delete=models.PROTECT. Wagtail does not allow simple database CASCADE because it will corrupt its tree storage.
home.HomeOnePage.site: (wagtailcore.W001) Field hasn't specified on_delete action
HINT: Set on_delete=models.SET_NULL and make sure the field is nullable or set on_delete=models.PROTECT. Wagtail does not allow simple database CASCADE because it will corrupt its tree storage.
home.HomePage.site: (wagtailcore.W001) Field hasn't specified on_delete action
HINT: Set on_delete=models.SET_NULL and make sure the field is nullable or set on_delete=models.PROTECT. Wagtail does not allow simple database CASCADE because it will corrupt its tree storage.
The problem is with the line:
objects = models.Manager()
Managers on Page models must inherit from wagtail.core.models.PageManager. However, in this case the manager is serving no purpose, and the line should simply be left out.
I am in process of creating Django CMS plugin. So far I have created a form, model and plugin file. I want to save SETTINGS info, but when I go to save it it gives error as mentioned above. Below are details.
cms_plugins.py
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from cms.models import CMSPlugin
from src.survey.forms import SurveyForm
from . import models
class SurveyPluginPublisher(CMSPluginBase):
"""Show Polls entered by Admin."""
cache = False
form = SurveyForm
model = models.SurveyPluginModel # Must add to show stuff.
module = "Survey"
name = "Awesome Survey v1.0"
render_template = 'survey/_hello.html'
plugin_pool.register_plugin(SurveyPluginPublisher)
forms.py
from django import forms
from src.survey.models import Survey
models.py
class SurveyForm(forms.Form):
# all_surveys = Survey.objects.only('name')
# surveys = forms.ModelChoiceField(queryset=all_surveys)
headline = forms.CharField(max_length=255, help_text='Enter Headline')
description = forms.CharField(widget=forms.Textarea(attrs={'rows': 5, 'cols': 100}),help_text='Enter Description')
models.py
class SurveyPluginModel(CMSPlugin):
name = models.CharField("Survey Name", max_length=255, default='Survey Name',
help_text='Enter Survey Name')
description = models.CharField("Survey Description", max_length=500, blank=True, help_text='Write Description here')
def __str__(self):
return "Returning some Survey Text"
SurveyForm should be a subclass of ModelForm
class SurveyForm(forms.ModelForm):
class Meta:
model = SurveyPluginModel
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 hava an article app installed in django admin site,when i finish editing one article,I click the save button,but an error page:
article/models.py
# blog category models
class Category(models.Model):
id = models.IntegerField(primary_key=True,help_text='primary key')
name = models.CharField(max_length=50,help_text='category name')
description = models.TextField(default='',help_text='category description')
createtime = models.DateTimeField(auto_now_add=True)
modifytime = models.DateTimeField(auto_now=True)
categories = models.Manager()
class Meta:
db_table = 'article_category'
def __str__(self):
return self.name
#blog article models
class Article(models.Model):
STATUS = (
(0,'on'),
(1,'off')
)
id = models.IntegerField(primary_key=True,help_text='primary key')
category = models.ForeignKey(Category,help_text='foreigner key reference Category')
title = models.CharField(max_length=100,help_text='article title')
content = models.TextField(help_text='article content')
like = models.IntegerField(default=0,help_text='like numbers')
secretcode = models.CharField(max_length=512,help_text='who has the code can scan')
status = models.IntegerField(choices=STATUS,help_text='status of the article')
createtime = models.DateTimeField(auto_now_add=True,help_text='time that first created')
modifytime = models.DateTimeField(auto_now=True,help_text='time when modified')
articles = models.Manager()
class Meta:
db_table = 'article'
article/widgets.py
from pagedown.widgets import AdminPagedownWidget
from django import forms
from .models import Article
class ArticleModelForm(forms.ModelForm):
content = forms.CharField(widget=AdminPagedownWidget())
class Meta:
model = Article
fields = ('title','category', 'content', 'secretcode', 'status')
article/admin.py
from django.contrib import admin
from .widgets import ArticleModelForm
from .models import Article,ArticleImage,Category
class MMBArticleAdmin(admin.ModelAdmin):
form = ArticleModelForm
admin.site.register(Article,MMBArticleAdmin)
admin.site.register(Category)
admin.site.register(ArticleImage)
the page in the admin site looks likeļ¼
and then I click save ,the error page show up like above!why did this happen?and how to fix it?
You've overridden the default automatic field with a manual non-autoincrementing ID. Don't do that. Remove your id fields altogether.
I've implemented a circular OneToMany relationship at a Django model and tried to use the limit_choices_to option at this very same class.
I can syncdb without any error or warning but the limit is not being respected.
Using shell I'm able to save and at admin I receive the error message:
"Join on field 'type' not permitted.
Did you misspell 'neq' for the lookup
type?"
class AdministrativeArea(models.Model):
type = models.CharField(max_length=1, choices=choices.ADMIN_AREA_TYPES)
name = models.CharField(max_length=60, unique=True)
parent = models.ForeignKey('AdministrativeArea',
null=True,
blank=True,
limit_choices_to = Q(type__neq='p') & Q(type__neq=type)
)
The basic idea for the limit_choices_to option is to guarantee that any type "p" cannot be parent ofr any other AdministrativeArea AND the parent cannot be of the same type as the current AdministrativeArea type.
I'm pretty new to Django ... what am I missing?
Thanks
You can create a model form that adjusts specific field's queryset dynamically when working with existing model instance.
### in my_app/models.py ###
class AdministrativeArea(models.Model):
type = models.CharField(max_length=1, choices=choices.ADMIN_AREA_TYPES)
name = models.CharField(max_length=60, unique=True)
parent = models.ForeignKey('AdministrativeArea',
null=True,
blank=True,
limit_choices_to = Q(type__neq='p')
)
### in my_app/admin.py ###
from django.contrib import admin
import django.forms as forms
from my_app.models import AdministrativeArea
class class AdministrativeAreaAdminForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(AdministrativeAreaAdminForm, self).__init__(*args, **kwargs)
instance = kwargs.get('instance', None)
if instance is not None:
parentField = self.fields['parent']
parentField.queryset = parentField.queryset.filter(type__neq=instance.type)
class Meta:
model = AdministrativeArea
class AdministrativeAreaAdmin(admin.ModelAdmin):
form = AdministrativeAreaAdminForm
Such form could be used also outside admin site if you need the filtering there.