Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"message": "Field 'id' expected a number but got 'Ashu'."
my modelfrom django.db import models import datetime from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) from django_countries.fields import CountryField class MyUserManager(BaseUserManager): def create_user(self, email, date_of_birth, password=None): """ Creates and saves a User with the given email, date of birth and password. """ if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), date_of_birth=date_of_birth, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, date_of_birth, password=None): """ Creates and saves a superuser with the given email, date of birth and password. """ user = self.create_user( email, password=password, date_of_birth=date_of_birth, ) user.is_admin = True user.save(using=self._db) return user class MyUser(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True) user_name=models.CharField(max_length=10,blank=True,null=True,unique=True) date_of_birth=models.DateField(null=True,blank=True) mobile_number=models.CharField(max_length=20,blank=True,null=True) address=models.CharField(max_length=100,blank=True,null=True) country=models.CharField(max_length=20,blank=True,null=True) joining_date=models.DateField(null=True,blank=True) Rating_CHOICES = ( (1, 'Poor'), (2, 'Average'), (3, 'Good'), (4, 'Very Good'), (5, 'Excellent') ) Rating=models.IntegerField(choices=Rating_CHOICES,default=1) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = MyUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['date_of_birth'] def __str__(self): return str(self.user_name) def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.is_admin class IntrestedIn(models.Model): game=( ('cricket','cricket'), ('football','football'), ('basketball','basketball'), ('hockey','hockey'), ('gym','gym'), ('baseball','baseball'), ) line=( ('Beginner','Beginner'), ('Intermediate','Intermediate'), ('Advance','Advance'), ) Sport=models.CharField(max_length=50,choices=game) Level=models.CharField(max_length=50,choices=line) image=models.FileField(blank=True, default="", upload_to="media/images",null=True) user=models.ForeignKey(MyUser,on_delete=models.CASCADE, related_name='select_user',null=True) def __str__(self): return str(self.Sport) class Session(models.Model): Host=models.ForeignKey(MyUser,on_delete=models.CASCADE) game=( ('cricket','cricket'), ('football','football'), ('basketball','basketball'), ('hockey','hockey'), ('gym','gym'), ('baseball','baseball'), ) Sport=models.CharField(max_length=20,choices=game) SPORT=( … -
Login Required is taking away my wagtail documents
@login_required def view_architect_page(request): args = {'user': request.user} return render(request, 'DEMOAPP/architect_page.html', args) This is my view. It redirects me to my login page and then allows me into the page after logged in but it doesnt display the wagtail information. I know its not working becuase when i "view live" in wagtail, the files show up... class ArchitectPage(Page): search_fields = Page.search_fields + [ ] # these are if adding a search to the website # content tab panels content_panels = Page.content_panels + [ MultiFieldPanel( [InlinePanel('architect_pdf', max_num=20, min_num=0, label="architect pdf")], heading="architect pdf" ), ] # what to call the panels on wagtail edit_handler = TabbedInterface([ ObjectList(content_panels, heading='Content'), ObjectList(Page.promote_panels, heading='SEO'), ObjectList(Page.settings_panels, heading='Settings', classname='settings'), classname settings adds the cog ]) class ArchitectDownloads(Orderable): page = ParentalKey(ArchitectPage, on_delete=models.CASCADE, related_name='architect_pdf') architect_pdf = models.ForeignKey( 'wagtaildocs.Document', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) panels = [ DocumentChooserPanel('architect_pdf'), ] This is my html which doesnt show up becuase of this login required view... <ul> {% for download in page.architect_pdf.all %} {# loop over the ArchitectDownload objects #} {% with doc=download.architect_pdf %} {# retrieve the Document object for each one #} <li><a href="{{ doc.url }}">{{ doc.title }}</a></li> {% endwith %} {% endfor %} </ul> Ive been commenting this in and out and can … -
Failed to build python app in Heroku; can't find newscatcher
In trying to push to heroku I am getting a "build failed" error. In checking the logs I see it's because of the following: ERROR: Could not find a version that satisfies the requirement newscatcher==0.1.0 (from -r /tmp/build_3ad91c7bdb0b7ae3e65e7d3b8ae455f7/requirements.txt (line 13)) (from versions: none) ERROR: No matching distribution found for newscatcher==0.1.0 (from -r /tmp/build_3ad91c7bdb0b7ae3e65e7d3b8ae455f7/requirements.txt (line 13)) ! Push rejected, failed to compile Python app. ! Push failed It looks like there's an incorrect version of the "newscatcher" library I am trying to use. However, this is the correct version according to PyPi. In addition I have already performed a pip3 freeze > requirements.txt in order to collect all dependencies I know to be relevant. How come the correct version of a git supported pip package is throwing this error? How do I fix this? -
I am using django ... all my css is working but <a> tag properties are not working like hover , visited is not working?
html css output base.html <div class="col-md-3 col-sm-4 col-xs-6 col-md-push-1"> <br> <h3>About Us</h3> <ul class="fh5co-footer-links"> <li><a href="{% url 'about_us' %}">Goal</a></li> <li><a href="{% url 'about_us' %}">Vision and aim</a></li> <li><a href="{% url 'about_us' %}">Achivement</a></li> <li><a href="{% url 'about_us' %}">Location</a></li> </ul> </div> i am using django all my css is wokring but the css of the tag is not working the css is not working of the tag why is this is because of the static links i tried everthing but dont know whats wrong -
Validating a django form if it needs to go through a calculator
I have this calculator program written in Django that will takes several inputs as a form. I won’t know if one of the field is invalid until I run it through the calculator. How can I raise a validation error without having to run the calculator.py twice, one through the clean() method to validate and again to output in the view. Is it possible to raise a validation error midway in the calculator.py? -
Djongo ArrayReferenceField to patch in the database
I can able to do patch operation in ArrayReferenceField after refreshing it is getting again whatever data before. while updating through the Django admin page I can do all the operations. -
Does not ignore db.sqlite3 file,even i specified in .gitignore in django project
in my Django project,i have already .gitignore file in root as well in django project but when i fire git status or git add . It adding all __pycache__ db.sqlite3 in repository. i need to remove those two things from my project. please help.! I tried all things like *.sqlite3, mom/*.sqlite3, mom/db.sqlite3 and db.sqlite3 in my both .gitignore file respectively. But anything not work in any directory. here is my main git ignore file .gitignore media *.sqlite3 **/__pycache__/** *.pyc here is my another git ignore file .gitignore media db.sqlite3 **/__pycache__/** *.pyc I also tried many possibilities from online resources but anything not working file structure MOM-PROJECT(local Repo) | ├───MOM (main project) | ├───media | │ └───media | ├───MOM | │ ├───migrations | │ └───templatetags | ├───userprofile | │ └───migrations | │ └───__pycache__ | ├───templates | │ ├───MOM | │ ├───userprofile | │ └───base.html | ├───manage.py | ├───requirements.txt | ├───db.sqlite3 | └───.gitignore [another created after main] | ├───README.md ├───.git └───.gitignore [Main] Umm Actually first i created .gitignore file in at main folder where .git folder(in project) exist. my media folder automatically removed and that worked fine. but when i added mom/db.sqlite3 or *.sqlite3 in main .gitignore it's not ignoring therefore i … -
DJANGO - INDEX ASSOCIATE A LINK RUNSERVR
could you help me? how can we associate the index page to the link 127.0.0.1:8000 ? -
unable to run migrate in Django using jython
i am using jython 2.7. when i am trying to migrate using the command Jython manage.py migrate APP_NAME the following error is showing. Please provide a CPython 2.7 bytecode file (.pyc) to proceed, e.g. run python -m py_compile /scratch/code/Stayflexi/StayflexiApp/idb_platform/migrations/0001_initial.py and try again. Alternatively provide proper CPython 2.7 execute command via cpython_cmd property, e.g. call jython -J-Dcpython_cmd=python or if running pip on Jython: pip install --global-option="-J-Dcpython_cmd=python" <package> -
how to make youtube dl download to the user's browser
I have this code that allows th user to search a video then it grabs the youtube video, after that i want the user to be able to download the video they search for to their system, but instead it is downloading to the project file. here is the code: from __future__ import unicode_literals import youtube_dl options = {'outtmpl': '%(title)s'+'.mp4'} with youtube_dl.YoutubeDL(options) as ydl: ydl.download(['https://www.youtube.com/watch?v=GD64pQOs1FQ']) thanks!!! -
Django override custom admin site's templates
I have two admin sites in my django app. One named admin and the other named owneradmin. I want to override their templates separately. Is there a way to do it ? -
ParseError at /landing_page not well-formed (invalid token):
Im working in django application to connect db im using mysql version 8.0, so my application is i created a UI if i upload a XML file it will generate a pdf. in that my application is working well. justnow i changed mysql server version 5.7. i connected my db, if i run my application while submit my xml file it showing a error ParseError at /landing_page not well-formed (invalid token): line 2060, column 70 tree = ET.parse(filename) #getting error in this line root = tree.getroot() -
Django FormView dont redirect on successfull POST
I'm currently writing a Chat-Application. In order to take User-Input, I use a Form and thus a FormView and a custom Form, following the Django-Docs. I have to set a success_url, but neither want to be redirected to another page on a successful POST, nor want i to reload the chat-page. How Do i go about that? I've read the following Post: Django FormView, Return without redirecting, but I dont really understand the Point of the Answer. Should I really avoid not redirecting? And if not, can I really achieve this with JQuery-Ajax? Doesn't that conflict with Django's success_url? Thanks for your Answers! -
Django with MySQL cluster
I was about to move my Django DB to a MySQL cluster. I have configured mysqlrouter and tested the connection to the db from the command line using the following command mysql --user=matrix --password --host=localhost --port=6446 --protocol=tcp and when I tried the same configuration (except protocol) on django it fails. And i'm unable to find a way to add protocol as an option in django. following is the django db configuration 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'matrix_db', 'USER': 'matrix', 'PASSWORD': 'matrix', 'HOST': '127.0.0.1', 'PORT': '6446', }, any help will be highly appreciated. Thanks in Advance. -
Django create a dropdown from a database model and save in another model
So I am new to Django and Python and would like to attempt the following. Create a dropdown list from the data in a model and save the data in another model . However everytime i render the form , it is invalid and does not display the template, Any help would be greatly appreciated. Please help where I am going wrong Models.py class Part(models.Model): category = models.TextField(default = ' ') def __str__(self): """String for representing the Model object.""" return self.category class UserItem(models.Model): name= models.CharField(max_length = 50, null=True) category = models.ForeignKey(Part, on_delete=models.SET_NULL, null=True) def __str__(self): """String for representing the Model object.""" return self.category Forms.py class DropDown(forms.ModelForm): name = forms.CharField() parts = forms.ModelChoiceField(queryset=Part.objects.values_list('category', flat=True).distinct()) class Meta: model = UserItem fields = ('name', 'category',) Views.py def index(request): query_results = Part.objects.all() #part_list = DropDown() if request.method == 'POST': form = DropDown(request.POST) if form.is_valid(): form.save() return render(request,'index.html', {'query_results': query_results }, {'form': form } ) else: print("invalid") print (DropDown.errors) form = DropDown() return HttpResponseRedirect(reverse('genre_create') ) -
How can i write unit test for class based view in django?
DISCLAIMER: I'm new to Django development. Say I have an ApplicationForm page view in my application as follows class Application(View): def get(self, request, *args, **kwargs): ... ... ... response = TemplateResponse(request, self.template_name, self.context) response.delete_cookie(conf.TRANSACTION_COOKIE_NAME) return response def post(self, request, *args, **kwargs): ... ... ... context.update({ 'error': 1, 'error_status': de_status_id, 'error_msg': error_msg, 'channel': channel, 'form': self.get_form_for_channel(channel)(self.post_params, channel=channel), }) return render(request, get_landingpage_template(channel, request.path, version), context) How can I write the unit test for this using django.test What I have tried is class BaseViewTest(object): longMessage = True # More verbose messages view_class = None def setUp(self): self.client = Client() def tearown(self): del self.client def is_callable(self, path): resp = self.client.get('/{0}'.format(path)) self.assertEqual(resp.status_code, 200) def is_returning_correct_view(self, path, view): resp = resolve('/{0}'.format(path)) self.assertEqual(resp.func.__name__, view) def is_correct_template(self, path, template): resp = self.client.get('/{0}'.format(path)) self.assertTemplateUsed(resp, template) And also unit test for checking correct template class TestApplicationPageView(BaseViewTest, SimpleTestCase): def test_application(self): self.is_callable('apply/') self.is_returning_correct_view('apply/', ApplicationPageHandler.as_view().__name__) self.is_correct_template('apply/', 'application.html') How can I write unit tests for get and post methods? -
Not displaying the popups and markups in the leaflet for the already inserted map using leaflet?
Here I want to add the code for search bar and popups: Unfortunately , popups are not showing in the map. Separetly , it is working for popups and searchbar. In this project, I am using the django and retreiving the data and showing the popups.I will add the image for the popups which is worked individually. **Actually i merged the two files here but search bar is only working please provide the code ** Thank you in advance <html> <head> {%load static %} <meta charset="utf-8" /> <title>Searching map services</title> <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" /> <!-- Load Leaflet from CDN --> <link rel="stylesheet" href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css" integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ==" crossorigin=""/> <script src="https://unpkg.com/leaflet@1.6.0/dist/leaflet.js" integrity="sha512-gZwIG9x3wUXg2hdXF6+rVkLF/0Vi9U8D2Ntg4Ga5I5BZpVkVxlJWbSQtXPSiUTtC0TjtGOmxa1AJPuV0CPthew==" crossorigin=""></script> <!-- Load Esri Leaflet from CDN --> <script src="https://unpkg.com/esri-leaflet@2.3.3/dist/esri-leaflet.js" integrity="sha512-cMQ5e58BDuu1pr9BQ/eGRn6HaR6Olh0ofcHFWe5XesdCITVuSBiBZZbhCijBe5ya238f/zMMRYIMIIg1jxv4sQ==" crossorigin=""></script> <!-- Load Esri Leaflet Geocoder from CDN --> <link rel="stylesheet" href="https://unpkg.com/esri-leaflet-geocoder@2.3.2/dist/esri-leaflet-geocoder.css" integrity="sha512-IM3Hs+feyi40yZhDH6kV8vQMg4Fh20s9OzInIIAc4nx7aMYMfo+IenRUekoYsHZqGkREUgx0VvlEsgm7nCDW9g==" crossorigin=""> <script src="https://unpkg.com/esri-leaflet-geocoder@2.3.2/dist/esri-leaflet-geocoder.js" integrity="sha512-8twnXcrOGP3WfMvjB0jS5pNigFuIWj4ALwWEgxhZ+mxvjF5/FBPVd5uAxqT8dd2kUmTVK9+yQJ4CmTmSg/sXAQ==" crossorigin=""></script> <style> body { margin:0; padding:0; } #map { position: absolute; top:0; bottom:0; right:0; left:0; width: 80%; height: 700px;} </style> </head> <body> <div id="map"></div> <script> var map = L.map('map').setView([16.91587, 82.159257999999], 10); L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '&copy; <a href="https://osm.org/copyright">OpenStreetMap</a> contributors' }).addTo(map); var arcgisOnline = L.esri.Geocoding.arcgisOnlineProvider(); L.esri.Geocoding.geosearch({ providers: [ arcgisOnline, L.esri.Geocoding.mapServiceProvider({ label: 'States and Counties', url: 'https://sampleserver6.arcgisonline.com/arcgis/rest/services/Census/MapServer', layers: [2, 3], searchFields: ['NAME', 'STATE_NAME'] }) ] }).addTo(map); var … -
Unable to savedata to database in Django using Model and Forms
I trying to to create a database panel for a restaurant app where a user can add, remove, view and create a menu for the restaurant. In this the user can add the name, cuisine, category(veg/non veg) and cost as details of the menu item. Here is my Models.py: class Cuisine(models.Model): cuisine = models.CharField(max_length=15) def __str__(self): return self.cuisine class Meta: verbose_name_plural = 'cuisines' class Category(models.Model): category_type = models.CharField(max_length=9) def __str__(self): return self.category_type class Meta: verbose_name_plural = 'category type' class Item(models.Model): name = models.CharField(max_length=50) cost = models.IntegerField() cuisine = models.ForeignKey(Cuisine, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self): return self.name Here is Forms.py: class ItemForm(forms.ModelForm): class Meta: model = Item fields = ['name', 'cost'] class CategoryForm(forms.ModelForm): class Meta: model = Category fields = ['category_type'] class CuisineForm(forms.ModelForm): class Meta: model = Cuisine fields = ['cuisine'] And below is my Views.py: @login_required() def add_item(request): if request.method == 'POST': itemform = ItemForm(request.POST or None) catform = CategoryForm(request.POST or None) cuisineform = CuisineForm(request.POST or None) if itemform.is_valid(): item = itemform.save(commit=False) ct = catform.save(commit=False) cui = cuisineform.save(commit=False) item.name = request.POST.get('name') cui.cuisine = request.POST.get('cuisine') ct.category = request.POST.get('category') item.cost = request.POST.get('cost') item.save() ct.save() cui.save() messages.success(request, 'Item added successfully!!') else: messages.warning(request, 'Unable to add the item.') return redirect('add_item') else: item_list … -
Updating instance of model in Django
I'm a beginner and trying to make a to-do list app. I want the app to display only the tasks that have not yet been marked completed (by the user). models.py: class Task(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=50) description = models.TextField(blank=True, null=True) start_date = models.DateTimeField() end_date = models.DateTimeField() priority = models.BooleanField(default=True) completed = models.BooleanField(default=False) def __str__(self): return self.title View: def task(request): task = Task.objects.filter(user=request.user, completed=False) queryset = task.order_by('-start_date') context = { 'task': queryset, } return render(request, 'task-list.html', context) I want to display an option (a link/button) for the user, which upon clicking would update the instance 'completed' to True (and so the task will no longer be displayed). I would like to use an achor tag as the button. something like <a href="{% url 'complete' id=obj.id %}">completed</a> I have created this view: def task_completed(request, id): get_task = Task.objects.filter(id=id) get_task.instance.completed = True return redirect('task:task-page') The urls.py: app_name = 'task' urlpatterns = [ path('', home, name='home-page'), path('task', task, name='task-page'), path('complete', task_completed, name='complete'), upon loading the task-list page, it shows Reverse for 'complete' not found. 'complete' is not a valid view function or pattern name. any help would be appreciated! -
Display SQL results in Django Admin interface
I have set up a Django Admin Interface (django.contrib.admin) to see my data from my Mysql Database. I would like to know if it's possible to make specifics SQL queries ? So far, all my tables are registered to be displayee in the Django Admin Dashboard by doing for example : # Register your models here. @register(User) class User(ModelAdmin): list_display = ('name', 'city') list_filter = ('name',) search_fields = ('name',) @register(Object) class Object(ModelAdmin): list_display = ('name', 'object_description', 'owner', 'acquired_date') list_filter = ('name',) Let's say, I would like to display a specific table in the dashboard showing all the users with the appropriate object and the date of acquisition. How could I do that ? Or, better, how can I display data from multiple JOIN query ? I saw the querySet function but I did not see any examples to do this kind of things. Thank for your help -
Django image.url returning values appended with random text
I am quite new to Django. I have made a django project, where I upload some images through admin panel. And a template which takes values from the model and display the images accordingly. This is working fine on Localhost and after first commit. Then when I checked after next commit no images can be found! Later I realized, media directory is being overwritten, and then I added a .gitignore file which contains: *.log *.pot *.pyc __pycache__/ local_settings.py db.sqlite3 media .env .venv env/ venv/ ENV/ env.bak/ venv.bak/ then, just for checking purposes, I edited some comments and recommitted. But same error happened again! Media folder is overwritten again! Could anyone highlight what I am missing here? my file structure: ├───media │ └───media ├───Personal_website │ ├───migrations │ └───templatetags ├───Resume │ └───migrations │ └───__pycache__ ├───templates │ ├───Personal_website │ ├───Resume │ └───Visitors ├───manage.py ├───requirements.txt ├───.gitignore ├───procfile ├───db.sqlite3 -
Django - itertools.chain on different models with different cols
I have two different models each with different columns connected by one id. I want to create a searh page that would search the result from both the models, joining them with the id and show the results. This is the simple sql i want to execute: 'SELECT "SSDatabase_metadataform".*, "SSDatabase_uploadmeta"."datafile", CASE WHEN "SSDatabase_metadataform"."Embargo_Time" <= current_date THEN "SSDatabase_uploadmeta"."path_id" END AS link from "SSDatabase_metadataform" INNER JOIN "SSDatabase_uploadmeta" ON "SSDatabase_metadataform"."id" = "SSDatabase_uploadmeta"."path_id" order by "id"' I creates a search query, and it works fine showing the data from one of the model and it does not show the col form the second model. I am not sure how to write a join statement to fetch the corresponding data from the second model class SearchResultsView(ListView): template_name = 'searchresults.html' def get_queryset(self): # new query = self.request.GET.get('q') meta_list= Metadataform.objects.filter(Q(id__icontains=query) | Q(Authors_Name__icontains=query) | Q(Affliations__icontains=query) | Q(Methods__icontains=query) | Q(Instruments__icontains=query) | Q(Software__icontains=query)| Q(Models__icontains=query)| Q(Device__icontains=query)) dataset_list = uploadmeta.objects.filter(Q(datafile__icontains=query)) object_list = list(chain(meta_list, dataset_list)) return object_list And this is my html page. The datafile from the other model is not fetched <table class="table table-striped"> <thead> <tr> <th>Meta ID</th> <th>Author</th> <th>Affiliations</th> <th>Methods</th> <th>Instruments</th> <th>Models</th> <th>Device</th> <th>Configuration</th> <th>Download</th> </tr> </thead> <tbody> {% if object_list %} {% for a in object_list %} <tr> <td><a id="idclicked" … -
how to set pagination in SQL query as per page?
how to set pagination as per page in SQL query, i tried with django default pagination but it didn't worked in my code and i am direct fetching data using SQL raw-query instead of ORM. i think the another way is set pagination using SQL query LIMIT or OFFSET but i have no idea about url-endpoint when i am searching next-page. class Order_ListAPIView(APIView): def get(self,request,format=None): if request.method == 'GET': cur,conn = connection() order_query = ''' SELECT * FROM orders''' order_detail_query = ''' SELECT * FROM order_details''' with conn.cursor(MySQLdb.cursors.DictCursor) as cursor: cursor.execute(order_query) order_result = cursor.fetchall() order_data = list(order_result) ... ... #rest_code ... return Response({"order_data":order_data},status=status.HTTP_200_OK) else: return Response(status=status.HTTP_400_BAD_REQUEST) -
How to disable suffix generated when upload on a FileField in Django?
I have a model which has a FileField. When I upload on that field, a suffix is generated. How do I disable adding this suffix? class RawFile(models.Model): file = models.FileField( upload_to=settings.RAW_IMAGE_UPLOAD_PATH, null=True, max_length=500 ) When I upload something like this: MFC_CAP190519_142958_976940_DEC190606_040944.rg3 It gets renamed to something like this: MFC_CAP190519_142958_976940_DEC190606_040944_gqHQEiE.rg3 -
How to make the documents downloadable from wagtail?
I have uploaded pdf's to my wagtail page but I cant work out how to get them to actually be downloadable from the web page itself. This is my code for the models.py file. What html code do I need to make these? class ArchitectPage(Page): pdf_files = models.ForeignKey( 'wagtaildocs.Document', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) search_fields = Page.search_fields + [ ] # these are if adding a search to the website # content tab panels content_panels = Page.content_panels + [ MultiFieldPanel( [InlinePanel('architect_pdf', max_num=20, min_num=0, label="architect pdf")], heading="architect pdf" ), ] # what to call the panels on wagtail edit_handler = TabbedInterface([ ObjectList(content_panels, heading='Content'), ObjectList(Page.promote_panels, heading='SEO'), ObjectList(Page.settings_panels, heading='Settings', classname='settings'), # classname settings adds the cog ]) class ArchitectDownloads(Orderable): page = ParentalKey(ArchitectPage, on_delete=models.CASCADE, related_name='architect_pdf') architect_pdf = models.ForeignKey( 'wagtaildocs.Document', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) panels = [ DocumentChooserPanel('architect_pdf'), ]