Django-ajax-selects with AJAX_SELECT_BOOTSTRAP = False - python

At work we are using django-admin webapp. I wanted to implement django-ajax-selects functionality to some of fields. Our network is isolated from Internet and I cannot use django-ajax-selects's CDNs. Documentation says that in such case you should set AJAX_SELECT_BOOTSTRAP to False in settings.py file. However, when I set this parameter, django-ajax-selects fails to use django's jquery.
Django's version is 1.11.10, Python2.
Steps to reproduce my issue:
pip install django==1.11.10 django-ajax-selects
django-admin startproject proj ./
python manage.py startapp test_app
python manage.py migrate
python manage.py createsuperuser
test_app/models.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
class Tag(models.Model):
name = models.CharField(max_length=100)
something = models.CharField(max_length=100)
def __str__(self):
return self.name
class SecondModel(models.Model):
name = models.CharField(max_length=200)
tag = models.ForeignKey(Tag, on_delete=models.CASCADE)
def __str__(self):
return self.name
test_app/lookups.py
from ajax_select import register, LookupChannel
from .models import Tag
#register('tags')
class TagsLookup(LookupChannel):
model = Tag
def get_query(self, q, request):
return self.model.objects.filter(name__icontains=q)
def format_item_display(self, item):
return u"<span class='tag'>%s</span>" % item.name
test_app/admin.py
# -*- coding: utf-8 -*-
from django.contrib import admin
from ajax_select import make_ajax_form
from .models import Tag, SecondModel
#admin.register(Tag)
class TagAdmin(admin.ModelAdmin):
fields = ['name', 'something']
#admin.register(SecondModel)
class SecondModelAdmin(admin.ModelAdmin):
form = make_ajax_form(SecondModel, {
'tag': 'tags'
})
proj/settings.py - adding the app and ajax_select to INSTALLED_APPS
INSTALLED_APPS = (
...
'ajax_select',
'test_app',
)
proj/urls.py
from django.conf.urls import url, include
from django.contrib import admin
from ajax_select import urls as ajax_select_urls
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^ajax_select/', include(ajax_select_urls)),
]
Then
python manage.py makemigrations test_app
python manage.py migrate
If I run the server like that it works absolutely fine (because it uses CDNs to load jquery and stuff).
But if I set AJAX_SELECT_BOOTSTRAP to False I will get a TypeError in browser's console and the ajax functionality will not work. I guess ajax_select.js just loads before django's jquery was loaded. I could not figure it out, how can I specify load order or may be there is another way? Template overriding would be not very good idea as there is some overriding already used by other apps and I'm afraid it can cause some conflicts.

In the end what I needed to do was to manually download jquery.min.js, jquery-ui.js, jquery-ui.css and also jquery-ui images library, put them into app's static directory and point to them in admin.py:
admin.py
...
#admin.register(SecondModel)
class SecondModelAdmin(admin.ModelAdmin):
form = SecondModelForm
class Media:
js = ["/static/js/jquery.min.js",
"/static/js/jquery-ui.js"]
css = {'all': ["/static/css/jquery-ui.css"]}
Also don't forget to run python manage.py collectstatic for static files to be copied to common static directory.

Related

How to change the database name display in django admin site?

Is it possible to change change the database name in django admin site?
Just like how I change the following:
admin.site.site_header = "Administrator"
admin.site.site_title = "Administrator"
admin.site.index_title = "Admin"
There are two options, you can do it manually, or you can do it through the help of an external python library
Manually
is by creating custom AdminSite
admin.py
from django.contrib.admin import AdminSite
from django.utils.translation import ugettext_lazy
class MyAdminSite(AdminSite):
# Text to put at the end of each page's <title>.
site_title = ugettext_lazy('My site admin')
# Text to put in each page's <h1> (and above login form).
site_header = ugettext_lazy('My administration')
# Text to put at the top of the admin index page.
index_title = ugettext_lazy('Site administration')
admin_site = MyAdminSite()
urls.py
from django.conf.urls import patterns, include
from myproject.admin import admin_site
urlpatterns = patterns('',
(r'^admin/', include(admin_site.urls)),
)
by using python package
you can use the python package called django-admin-interface
pip install django-admin-interface
you'll need to import it into your settings.py
INSTALLED_APPS = (
#...
"admin_interface",
"flat_responsive", # only if django version < 2.0
"flat", # only if django version < 1.9
"colorfield",
#...
"django.contrib.admin",
#...
)
# only if django version >= 3.0
X_FRAME_OPTIONS = "SAMEORIGIN"
SILENCED_SYSTEM_CHECKS = ["security.W019"]
after installing it, you'll be able to customize your admin panel from the themes menu inside your admin panel
You can change the app name by adding verbose_name under app.py
from django.apps import AppConfig
class PharmacyConfig(AppConfig):
name = 'pharmacy'
verbose_name = 'Your Home Page'

When I try to add a new product to my PRODUCTS group in the Django Admin site it gives me a no such table: main.auth_user__old error

I've been learning python and Im having a problem when I try to add another user/group or anything in the admin page for Django. When I try to save it brings me to a page that says OperationalError at /admin/products/product/add/
no such table: main.auth_user__old.
I've been looking around and Ive found no fix for the problem I would like some help. This is some of the code.
This is my models.py code.
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=255)
price = models.FloatField()
stock = models.IntegerField()
image_url = models.CharField(max_length=4036)
class Offer(models.Model):
code = models.CharField(max_length=10)
description = models.CharField(max_length=255)
discount = models.FloatField()
This is the main url.py code
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('products/', include('products.urls'))
]
This is the secondary url.py code in my products folder
from django.urls import path
from . import views
#
# /products/1/detail
# /products/new
urlpatterns = [
path('', views.index),
path('new', views.new)
]
This is the views.py code
from django.http import HttpResponse
from django.shortcuts import render
def index(request):
return HttpResponse('Hello World')
def new(request):
return HttpResponse('New Products')
and finally this is the admin.py code
from django.contrib import admin
from.models import Product
admin.site.register(Product)
Does anyone know a fix for why when I try to add another product to my PRODUCTS group in the Django admin site and save it is says
OperationalError at /admin/products/product/add/
no such table: main.auth_user__old
Request Method: POST
Request URL: http://127.0.0.1:8000/admin/
Django Version: 3.1.7
Exception Type: OperationalError
Exception Value:
no such table: main.auth_user__old
Exception Location: C:\Users\jerem\PycharmProjects\PyShop\venv\lib\site-
packages\django\db\backends\sqlite3\base.py, line 413, in execute
Python Executable: C:\Users\jerem\PycharmProjects\PyShop\venv\Scripts\python.exe
Python Version: 3.9.2
Make sure your migration has been done correctly and that you have not changed significant attributes of the product model since the last migration.
Also check you database connection
I did this in pycharm and it did work:
pip install Django --upgrade
Then
python manage.py migrate
python manage.py makemigrations 'app_name'
python manage.py migrate
Put that in the terminal.
It took me like 5 hours to find the fix but this does work on pycharm!

Add view in the bottom of Django modeladmin

I have a blog made with Django where I write posts in markdown. I would like to add a view in the bottom of the admin page for each instance of the class Entry (my blog post class) such that I can get a preview of what the markdown looks like, while I'm writing. Just as you get a preview here on Stack Overflow when you create a new post.
I already have an admin class extending ModelAdmin:
class EntryAdmin(admin.ModelAdmin):
list_display = ('title','created')
prepopulated_fields = {'slug': ('title',)}
Is it possible to modify ModelAdmin further, such that it loads a certain html file (blogpost.html) and shows it in the bottom of the admin page?
I made a picture to show exactly what I mean:
NB: I know there are various tools such as Django admin plus, that allows one to add views to the admin interface, but not for each instance of an object.
You can use markdownx for that:
pip install django-markdownx
project settings.py
INSTALLED_APPS =
#. . . .
'markdownx',
]
project urls.py
urlpatterns = [
#[...]
url(r'^markdownx/', include('markdownx.urls')),
]
and then collect static files.
python3 manage.py collectstatic
your models.py
from markdownx.models import MarkdownxField
class MyModel(models.Model):
myfield = MarkdownxField()
your app admin.py
from django.contrib import admin
from markdownx.admin import MarkdownxModelAdmin
from .models import MyModel
admin.site.register(MyModel, MarkdownxModelAdmin)
This should work.

Why is python manage.py makemigrations stalling in my python app?

I have a python application that uses Django models for easy storage of data. It is NOT a django app, I'm just attempting to use models from django.db, JSONField from django.contrib.postgres.fields and other useful parts.
When I attempt to run python manage.py makemigrations, the terminal stalls. How do I debug this?
Here are some snippets of my code:
manga_shell/models.py
import os, django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "manga_project.settings")
django.setup()
from django.db import models
from django.contrib.postgres.fields import JSONField
class Manga(models.Model):
# fields
class Chapter(models.Model):
# fields
class Page(models.Model):
# fields
manga_project/settings.py
import dj_database_url, os
SECRET_KEY = #secret :P
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
INSTALLED_APPS = (
'django.contrib.postgres',
'manga_shell',
)
DATABASES = {'default': dj_database_url.config(default='postgres://MyUserName:MyPassword#localhost:5432/manga_project_db')}
TIMEZONE = 'Asia/Kolkata'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
If more code is required, I'll post it. I'm not entirely clear on what might cause manage.py to stall, so I don't know for sure which snippets of code are needed. Thanks in advance for the help.

Practical Django Projects - Pages 71 and 80

I am reading the book "Practical Django Projects". It is a nice book. I have a few questions though :
On page 71, there is the following code :
from django.conf.urls.defaults import *
from django.contrib import admin
admin.autodiscover()
from coltrane.models import Entry
entry_info_dict = {
'queryset': Entry.objects.all(),
'date_field': 'pub_date',
}
...
However no variable 'pub_date' has yet been defined in that file !
On page 80, I am being told that I should place two variables DELICIOUS_USER and DELICIOUS_PASSWORD in the Django settings file. I should then call that file with
from django.conf import settings
Where is that Django settings file ? In C:\Python27\Lib\site-packages\django\conf ?
pub_date refers to coltrane.models.Entry attribute pub_date see the source
from django.conf import settings imports your project settings.py so you have to define your settings inside your project/settings.py file. Here are some docs on the official docs about using settings in python code
pub_date is referencing a field defined in the Entry model. Django will look up the field by name later, which is why it's in quotes (otherwise it would trigger an NameError).
In models.py, you should have something like:
class Entry(models.Model):
...
pub_date = models.DateField(...)
The settings file is typically called settings.py, and is located in your project's root folder (next to manage.py, etc.).

Categories

Resources