Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django external mysql db connection in test complains "unknown database"
In my django project I have a few database connections: eg. DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql_psycopg2", "NAME": "awesome", ... }, "other_1": { "ENGINE": "django.db.backends.postgresql_psycopg2", "NAME": "other_1", "TEST": {"MIRROR": defalut} ... }, "other_2": { "ENGINE": "django.db.backends.mysql", "NAME": "other_2", "TEST": {"MIRROR": defalut} } } Note: 1. The default and other_1 both are postgres backends and other_2 is mysql backend. 2. I added "TEST": {"MIRROR": defalut} to the extra database config in a bid to avoid those databases being created during test. See this link. Problem: When I run the test, it complains about Unknown database 'test_awesome', the stack trace shows it's from MYSQL backend: Traceback (most recent call last): File "/Users/jlin/virtualenvs/awesome-1SH6mAZ2/lib/python3.6/site-packages/django/test/testcases.py", line 1005, in setUpClass if not connections_support_transactions(): File "/Users/jlin/virtualenvs/awesome-1SH6mAZ2/lib/python3.6/site-packages/django/test/testcases.py", line 970, in connections_support_transactions ... File "/Users/jlin/virtualenvs/awesome-1SH6mAZ2/lib/python3.6/site-packages/MySQLdb/__init__.py", line 85, in Connect return Connection(*args, **kwargs) File "/Users/jlin/virtualenvs/awesome-1SH6mAZ2/lib/python3.6/site-packages/MySQLdb/connections.py", line 204, in __init__ super(Connection, self).__init__(*args, **kwargs2) django.db.utils.OperationalError: (1049, "Unknown database 'test_awesome'") If I comment out the other_2 connection, the test runs fine. -
Django postman integration issues
i'm currently trying to setup postman for django, see: https://bitbucket.org/psam/django-postman/wiki/Home What i did so far: Install the app package 'django-postman' added 'postman' to installed apps added postman settings to settings.py: POSTMAN_DISALLOW_ANONYMOUS = True POSTMAN_DISALLOW_MULTIRECIPIENTS = True POSTMAN_DISALLOW_COPIES_ON_REPLY = True POSTMAN_DISABLE_USER_EMAILING = True POSTMAN_AUTO_MODERATE_AS = True POSTMAN_MAILER_APP = None POSTMAN_I18N_URLS = False POSTMAN_QUICKREPLY_QUOTE_BODY = False POSTMAN_NOTIFIER_APP = None added the following blocks to my base.html: {% load bootstrap4 %} {% load staticfiles %} {% load postman_tags %} {% load i18n static %} {% block title %}{% endblock %} {% block extrahead %}{{ block.super }} <title>{{ settings.SITE_NAME }}</title> ... {% endblock %} {% block postman_menu %} <ul id="postman_menu">{% postman_unread as unread_count %} <li><a href="{% url 'postman:inbox' %}">&raquo;&nbsp;{% trans "Inbox" %}{% if unread_count %} <strong>({{ unread_count }})</strong>{% endif %}</a></li> <li><a href="{% url 'postman:sent' %}">&raquo;&nbsp;{% trans "Sent Messages" %}</a></li> <li><a href="{% url 'postman:write' %}">&raquo;&nbsp;{% trans "Write" %}</a></li> <li><a href="{% url 'postman:archives' %}">&raquo;&nbsp;{% trans "Archives" %}</a></li> <li><a href="{% url 'postman:trash' %}">&raquo;&nbsp;{% trans "Trash" %}</a></li> </ul> {% endblock %} added postman-urls to urls.py: url(r'^messages/', include('postman.urls', namespace='postman', app_name='postman')), now i got two question: app_name='postman' at urls.py is depricated since django 1.9 i guess, how to workaround here? simply removing it seems to work but im not sure... … -
How would I link a ChartJS doughnut chart to completed lists that contain a checklist?
How would I go about linking a ChartJS doughnut chart to several tasks when they are checked off as "completed"? Think of a 5 lists in Trello with items checked off within each one. And once the overall progress bar reaches 100% on each of the 5 lists, the ChartJS chart increases by 20% for each one. Acting almost an overall Progress Gauge. I'm guessing that I would need some type of conditional statement within the JS. Thanks -
How does Django manage Proxy models?
I understand the purpose of proxy models, but I have no clue as to how Django keeps track of them without (from the looks of it) storing some parent-child map in the database. For the following models: class Foo(models.Model): foo_field = CharField(...) class Bar(Foo): class Meta: proxy = True An appname_foo table (and no Bar-specific table) will be created. Compare this to standard table inheritance, where a new table with a foo_ptr column will be created. How is it possible for me to perform queries with the Bar model and get Bar, rather than Foo, objects without some sort of Bar-Foo mapping at the database level? -
Web Sockets not working in Django app on Heroku
I am trying to run my first django app on heroku, I managed to successfully deploy the app and everything works besides the web sockets. Locally I used in memory channels and everything worked. I tried on heroku both in memory channels and redis and both does not work. I tried many different configs but I couldn`t figure out any working solution. Also the heroku logs give me no clue what could be wrong.. The error that I get in browser: join_game.js:222 WebSocket connection to 'wss://battleships-war.herokuapp.com/game/20' failed: Error during WebSocket handshake: Unexpected response code: 404 Javascript client code: [I tried ws and wss prefixes and both crash ] var ws = new WebSocket((window.location.protocol == 'http') ? 'ws://' : 'wss://' + window.location.host + '/game/' + gameId); redis config in settings.py CHANNEL_LAYERS = { "default": { "BACKEND": "asgi_redis.RedisChannelLayer", "CONFIG": { "hosts": [('ec2-34-254-133-4.eu-west-1.compute.amazonaws.com', 26849)], }, 'ROUTING': 'battleships.routing.channel_routing', }, } optional in memory config which worked locally: CHANNEL_LAYERS = { 'default': { 'BACKEND': 'asgiref.inmemory.ChannelLayer', 'ROUTING': 'battleships.routing.channel_routing', }, } redis credentials from heroku: Host: ec2-34-254-133-4.eu-west-1.compute.amazonaws.com User Port 26849 Password URI: redis://h:p69877187246d4f0b36a94488814ee0b372234a2e943a61df0cdc84e4f85f35f2@ec2-34-254-133-4.eu-west-1.compute.amazonaws.com:26849 procfile: web: gunicorn battleships.wsgi --preload heroku logs: 2019-01-14T21:06:52.847189+00:00 heroku[web.1]: State changed from up to starting 2019-01-14T21:07:00.911326+00:00 heroku[web.1]: Starting process with command gunicorn battleships.wsgi --preload … -
How you pass a queryset in a Django ManyToManyField. Error: int() argument must be a string, a bytes-like object or a number, not 'QuerySet'
Intro: Lets say I have a Feeds model which has a user and followers. When a user writes a post. All his followers get a feed on their homepage that the person they are following wrote a post. class Feed(models.Model): being_followed = models.ForeignKey(User, blank=True, null=True, related_name="feeds_for_followers") follower = models.ManyToManyField(User, blank=True, related_name="homepage_feeds") being_followed_post = models.ForeignKey(Post, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) My issue: Now if you see the post_create view below. The user is request.user the post is the post. However I am adding followers with the code users_followers = post_user.followers.all() for follower in users_followers: feed.follower.add(follower) which is very inefficient. Is there a way I can add the entire queryset users_followers to the followers ManytoManyField I tried followers = user.followers.all() feed.follower.add(followers) I get the below error int() argument must be a string, a bytes-like object or a number, not 'QuerySet' Below is my views.py @login_required def post_create(request): ... #code to create post instance.save() feed = None try: feed = Feed.objects.create(being_followed=post_user, being_followed_post=instance) except IntegrityError: messages.warning(request, ("Something went wrong with feed creating feed for: {}".format(instance.title))) else: feed.save() #Please pay attention to the code below this is where the followers are added to the feed model for follower in post_user.followers.all(): feed.follower.add(follower) return redirect('posts:single', username=instance.user.username, slug=instance.slug) -
Django set user(employees) permission to interact with the app based on their department
I have one django app that adds purchase orders to a database. I want to have give users permission to interact with app based on which department they are from, office or factory. Members from the office can edit, add and delete orders where as I want members from the factory to just view orders. I'm confused if I should create a seperate for every department which I mean I'll repeat code. I wanted to know if there's any other way I can do this. Note: I'm aware of the permissions in the Django admin. -
Does django handle default cookies? if so, how reliable are they? How do they work? [on hold]
I'm trying to develop a simple web app which will have blogs. I need to know id django collects cookies by default. If so how to see what cookies do they collect. If not is there a way to collect cookies. Please help! Thank you in advance :) -
Save excel file from main directory to database model in Django
How to save the file generated from pd.dataframe to certain database record. This is the view.. @csrf_exempt def Data_Communication(request): if request.method == 'POST': data_sets_number = (len(request.POST)) - 1 Data_Sets_asNestedList = [] Data_set_id = request.POST.get('id') Data_instance = Data_Sets.objects.get(pk=Data_set_id) for x in range(data_sets_number): i = 1 Data_Sets_asNestedList.append(request.POST.getlist('Data'+str(i))) i = i + 1 pd.DataFrame(Data_Sets_asNestedList).to_excel('output.xlsx', header=False, index=False) print(Data_Sets_asNestedList) return HttpResponse('1') -
Getting django model errors for a model I am trying to delete
Can you help? I made a mistake on my Django models.py and wanted to then delete the model. As you can see from the below, the migration was to delete the model called code. However, it still errors & doesn't delete the model. What can I do? root@new:/home/django/django_project# python manage.py makemigrations Migrations for 'netshock': netshock/migrations/0018_delete_code.py - Delete model code root@new:/home/django/django_project# python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, netshock, sessions Running migrations: Applying netshock.0012_code...Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/lib/python2.7/dist-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/usr/lib/python2.7/dist-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/lib/python2.7/dist-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/usr/lib/python2.7/dist-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/usr/lib/python2.7/dist-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/usr/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/usr/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/usr/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "/usr/lib/python2.7/dist-packages/django/db/migrations/migration.py", line 129, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/usr/lib/python2.7/dist-packages/django/db/migrations/operations/models.py", line 97, in database_forwards schema_editor.create_model(model) File "/usr/lib/python2.7/dist-packages/django/db/backends/base/schema.py", line 303, in create_model self.execute(sql, params or None) File "/usr/lib/python2.7/dist-packages/django/db/backends/base/schema.py", line 120, in execute cursor.execute(sql, params) File "/usr/lib/python2.7/dist-packages/django/db/backends/utils.py", … -
How to check USER exists using Javascript
TL;DR How to check user exists using Javascript (Ajax?) if a given user is in the database after reading a bar code / qr code. The backend of the project is written in Django and the frontend is pure JavaScript & jQuery. Django: The project divides the users into three type: 'client', 'company', 'user'. 'User' is assigned to 'company', and 'client' can check if the 'user' is active (is_active = True) The 'user', when registering, gets a twelve-digit number assigned along with a bar code. models.py class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=100, unique=True) first_name = models.CharField(max_length=150, blank=True) last_name = models.CharField(max_length=150, blank=True) email = models.EmailField(max_length=255, unique=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) date_joined = models.DateTimeField(('date joined'), auto_now_add=True) account_type = models.CharField(max_length=50, choices=ROLES, blank=True) barcode = models.CharField(max_length=12, null=True, blank=True, unique=True) employer = models.ForeignKey(Employer, on_delete=models.CASCADE, null=True, blank=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', ] objects = UserManager() def get_short_name(self): return self.username def __unicode__(self): return self.email Javascript: On the 'dashboard' page, I have a bar code scanner implemented (https://serratus.github.io/quaggaJS/), and only the client has access to it. After reading the code, a photo with the code appears on the page, and a new id appears, which stores the number read from the … -
ModuleNotFoundError: but only appears when I start the debugger in pycharm
Sorry - I have read all the similar issues among the posts but none of them solved my issue. I am getting the below error when I try to open the debugger in pycharm(the app is working on a local server otherwise): ModuleNotFoundError: No module named 'main.forms'; 'main' is not a package my project structure: see my project directory in my views.py under the app1 folder I need to reference a form class from the same directory: from .forms import RestaurantForm if I try it without the dot, but I get another error: ImportError: attempted relative import with no known parent package -
type object 'ModelForm' has no attribute 'ValidationError'
I am trying to create a registration form (using Django ModelForm) where I want to validate if the 'password' and confirm password match. I tried using the raise ValidationError but I get an error saying type object 'ModelForm' has no attribute 'ValidationError' What should be the correct way to validate the passwords? Here's my code below: models.py: from django.db import models class Students(models.Model): firstName = models.CharField(max_length=120) lastName = models.CharField(max_length=120) # studentID = models.IntegerField(null=False) email = models.EmailField() password = models.CharField(max_length=120, default="") password2 = models.CharField(max_length=120, default="") street = models.CharField(max_length=120) apt = models.IntegerField(blank=True, null=True) city = models.CharField(max_length=120) state = models.CharField(max_length=120) zipcode = models.IntegerField(null=False) def __str__(self): return self.firstName class Meta: verbose_name_plural = "Students" forms.py: from django.forms import ModelForm from django.utils.translation import gettext_lazy as _ from .models import Students class StudentRegisterForm(ModelForm): class Meta: model = Students fields = [ 'firstName', 'lastName', 'email', 'password', 'password2', 'street', 'apt', 'city', 'state', 'zipcode', ] labels = { 'firstName': _('First Name'), 'lastName': _('Last Name'), 'password2': _('Confirm Password'), 'Apt': _('Apt/House'), 'zipcode': _('Zip Code'), } def clean(self): data = self.cleaned_data password = self.cleaned_data.get('password') print(password) password2 = self.cleaned_data.get('password2') if password2 != password: raise ModelForm.ValidationError("Passwords must match!") return data Views.py: from django.http import HttpResponseRedirect from django.shortcuts import render from .models import Students from .forms … -
Django: search query does not exist error
I am trying to compare 2 lists, one is pulled from the DB and the second one is a list which is being compared with, before updating the DB fields with the right information. Note, the following code is for brevity to get this point across - proof of concept. # create a list db_list = [] # fetch the DB and store them in the list. # db_list will contains: ['D01', 'D02', 'D03', 'D04', 'D05', 'D06'] for each in User.objects.all(): db_list.append(each.username) # new list that needs to be added to DB, also contains some overlaping data from db_list. second_list = ['XY12','D01','VA02','HM01','D04','HM03','D126'] # just a counter to loop through cc = 0 for each in second_list: # for each item on the second_list we need to check if that value # already exists in the DB, if so update its value with the current time. # If not, pass to else and create a new record. if second_list.count(db_list[cc]): model = User.objects.get(username=each) model.last_seen = timezone.now() model.save() else: # this method of initialising might not be the correct way but this works :/ model = User() gg = gg() model.username = each model.last_seen = timezone.now() # this is a foreignkey in the … -
setUpClass() is being called multiple times in DRF
Perhaps I am missing the logic but I want to add two unique records to a model then run my tests on an API. But my API complains .get() has returned 2 records, raising the error. I notice the error happens on my .post() check, while the get methods work well. Is it a bug? only enough if I change self.client.post with .get(), it doesn't complain. I have tried setUpTestData() since my database supports Transactions to no avail. Essentially, I want to try the get method and the post methods. All the get operations pass but on the post test, it fails. class ResetPwdTest(APITestCase): """ Test module for resetting forgotten password """ @classmethod def setUpClass(cls): super().setUpClass() cls.valid_payload = '1234567890ABCDEF' cls.expired_payload = '1234567ACDES' cls.invalid_payload = 'invalid0000' user_info = {'first_name': 'John', 'email': 'kmsium@gmail.com','password' : 'kigali11', 'status': 1} user = User.objects.create_user(**user_info) PasswordReset.objects.all().delete() # delete any possible we have but having no effect so far # create valid password token password2 = PasswordReset(profile_id=user.id, unique_code=cls.valid_payload) password2.save() # create an expired passwod token password = PasswordReset(profile_id=user.id, unique_code=cls.expired_payload) password.save() password.createdon = '2018-01-12 21:11:38.997207' password.save() def test_valid_token(self): """ GET Ensure a valid forgotten password reset token returns 200 WORKING """ response = self.client.get(reverse('new-pwd', kwargs= {'token' : self.valid_payload})) self.assertEqual(response.status_code, … -
A view that is both add/edit (and urls to support) to essentially do an update_or_create in django
Is there a django way to create a view that does both an add and an update. I essentially have a table that is and will always hold one record the client will enter. But I need a way to let them enter this first record but then always edit it there on out. Most tutorials and pieces of code I have for an example essentially have very specific update views and create views and the update views/create views success urls return what is assumed to be a list of items for futher editing...(probably from some blog post demo somewhere). I could get this to work hacking those ways, but just figured there was a simpler django way to do what I want. I suspect also someone might say just do an UpdateView with an update_or_create at the start if the item does not exist, which would probably work somehow though I think I would have to put in default information ? -
Django on button click call function view
I have a list of matches which I get from my class based view: class MatchListView(LoginRequiredMixin, generic.ListView) In template I have a rows with list of matches and in one column I have a button. What I want to do is when I click on this button, another funcation/view is called, that takes that match id, and user, and saves it to database. I have done something like this: template <td><a href="{% url 'match_register_request' match.id %}" class="btn btn-info btn-sm">Zgłoś się na mecz</a></td> url path('match_register_request/<int:pk>', views.MatchRegisterViewRegister.as_view(), name='match_register_request') and the view: class MatchRegisterViewRegister(LoginRequiredMixin, generic.View): def post(self, request, object_id, *args, **kwargs): # Add record to DB mr = MatchRegister(match=object_id, ref_reg=self.request.user) mr.save() return redirect('matches_list') but it doesn't work. It takes the id, redirects to the url "matches_register_request/{ID}" but does nothing. Could you please help me with getting this done? -
how to remove b' from <class:str> in python 3
I'm trying to get the lines from a text file using Django in python3 here is the view def cat_tool(request): file_upload_form = FileUpload(request.POST, request.FILES) if request.method == 'POST': if file_upload_form.is_valid(): file = file_upload_form.cleaned_data['file'] file_content = file.read().splitlines() file.close() for line in file_content: print(line) else: file_upload_form = FileUpload(request.POST, request.FILES) context = { 'file_upload_form': file_upload_form, } return render(request, 'cat_tool.html', context) But the problem that it gives me every line starting with b' important am using file.read().splitlines() instead of file.readline() to remove the trailing 'b\'n\ after every line Also when I tried print(line) it gave me <class 'str'> -
How do I convert PySNMP's nextCmd on a table to multiple objects
When PySNMP's nextCmd() iterates over the table I am working with, it outputs by column, rather than by row. This has proven difficult when trying to save the data into an Object. For example, I will see every value from the alarmID column before moving on to the next column. So far, I've only created a print statement to output and see how the values are structured. I've been trying to think of a way to solve this, and my mind tends to take me to recursion, but it's something I haven't tried implementing yet. Here is the function I am working with: def query_alarm_table(device): manufacturer = Manufacturer(device.manufacturer) for (errorIndication, errorStatus, errorIndex, varBinds) in nextCmd( SnmpEngine(), CommunityData("public"), UdpTransportTarget((device.ip_address, device.snmp_port_number)), ContextData(), ObjectType(ObjectIdentity(manufacturer.alarm_table)), lexicographicMode=False, ): if errorIndication: print(errorIndication) break elif errorStatus: print("%s at %s" % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or "?",)) break else: for oid, raw_value in varBinds: print(f'oid: {oid} --- raw_value: {raw_value}') This above function is properly iterating over the table. But I am unsure of how to work with the data as if it were a single row and put it into an Object within my database. -
Pass Dynamic Value to Django url built-in
Within a view, I am maintaining a dictionary containing some data I would like to display in an <a> in a template with the Django url built-in. my_view.py links = [ { 'name': 'link 1', 'pattern': 'fe:upload' }, { 'name': 'link 2', 'pattern': 'fe:download' } ] It will work hardcoded like this: up down However I'm struggling to put it into a loop my_template.html <ul> {% for link in links %} <li> <a href='{% url link.pattern id %}'>{{link.name}}</a> </li> {% endfor %} </ul> I have tried: escaping the quotations with \ and HTML entities putting the href into a temp variable, eg: {% with href=url 'link.pattern' %} and get the error: u'with' received an invalid token: u"'link.pattern'" how can I put a dynamic pattern into this loop to generate an anchor? -
Generate iterable choices tuple from model class in Django
I'm working on a django model and I want to generate a tuple out of my model instances : model.py class Extra(models.Model): extra_n = models.CharField(max_length=200) extra_price = models.IntegerField(default=0) def __str__(self): return self.extra_n The output I'm expecting based on the user entries on the form associated : choices = (('extra_price 1','extra_n1'), ('extra_price 2','extra_n2'), ('extra_price 3','extra_n3') ) -
ImportError: Couldn't import Django in creating a database
i am trying to create database using django but getting following error: (myvenv) C:\Users\hp\djangogirls>myvenv\Scripts\activate (myvenv) C:\Users\hp\djangogirls> python manage.py migrate Traceback (most recent call last): File "manage.py", line 8, in from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 14, in ) from exc ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? -
handling subprocess file output
I am working on a project in which at some point user uploads a video and in backend i have to generate thumbnail for that video. I preferred ffmpeg for this purpose and the system is in django environment. This is my view function def upload(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = Document(docfile=request.FILES['docfile']) filename = str(request.FILES['docfile'].name) newdoc.save() op = subprocess.call(['ffmpeg', '-i',"media/private/"+up, '-ss', '00:00:03.000', '-vframes', '1', 'abc.jpg']) // Generates thumbnail newdoc.thumbnail = op newdoc.save() return HttpResponseRedirect(reverse('list')) else: form = DocumentForm() The Document has the thumbnail field. I know that subprocess.call() returns returncode not any object so using op variable is useless. So my query is how do i save generated thumbnail in model. -
how to convert django-rest-framework to list of json data
class AdvanceSearchViewSet(viewsets.ReadOnlyModelViewSet): queryset = SeekerRegister.objects.all() serializer_class = MainSeekerSerializer def get_queryset(self): queryset = SeekerRegister.objects.all() return queryset In the browser i am getting actual api. but in console when i am printing the queryset <QuerySet [<SeekerRegister: soubhagya>]> it is coming thike this. How can i get it in json format when i print in console. Because i have to edit the data before send it to the browser. -
Wagtail Custom URL based on slugs using RoutablePageMixin
I would like to change the URL for a blog entry to include the slug for category (@route(r'^([category-slug]/[post-slug] - e.g. localost/health/health_blog_1). How would I change the model for this? class PostPage(RoutablePageMixin, Page): body = RichTextField(blank=True) date = models.DateTimeField(verbose_name="Post date", default=datetime.datetime.today) categories = ParentalManyToManyField('blog.BlogCategory', blank=True) tags = ClusterTaggableManager(through='blog.BlogPageTag', blank=True) content_panels = Page.content_panels + [ FieldPanel('body', classname="full"), FieldPanel('categories', widget=forms.CheckboxSelectMultiple), FieldPanel('tags'), ] settings_panels = Page.settings_panels + [ FieldPanel('date'), ] @property def blog_page(self): return self.get_parent().specific def get_context(self, request, *args, **kwargs): context = super(PostPage, self).get_context(request, *args, **kwargs) context['blog_page'] = self.blog_page return context