UPDATE- It currently works in Safari but not chrome.
I was building an app and had the image upload section working previously, however, 2 weeks on in the project for some reason the upload file button in Django admin is no longer doing anything when clicked.
I can't work out what is blocking it as it's in the admin, Any suggestions?
This is for any of the apps in the project. This is the admin.py
from django.contrib import admin
from desire import models
admin.site.register(models.Desire)
admin.site.register(models.RelatedProduct)
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from account.models import Account
class AccountAdmin(UserAdmin):
list_display = ('email','username','date_joined', 'last_login', 'is_admin','is_staff')
search_fields = ('email','username',)
readonly_fields=('id', 'date_joined', 'last_login')
filter_horizontal = ()
list_filter = ()
fieldsets = ()
admin.site.register(Account, AccountAdmin)
settings
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
INSTALLED_APPS = [
# my APPs
'personal',
'account',
'ckeditor',
'ckeditor_uploader',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'channels',
'bootstrap4',
'fontawesome',
'cropperjs',
'django.contrib.humanize',
]
AUTH_USER_MODEL = 'account.Account' # TODO: ADD THIS LINE.
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.AllowAllUsersModelBackend',
'account.backends.CaseInsensitiveModelBackend',
)
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
DATA_UPLOAD_MAX_MEMORY_SIZE = 10485760
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
os.path.join(BASE_DIR, 'media'),
]
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static_cdn')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media_cdn')
TEMP = os.path.join(BASE_DIR, 'media_cdn/temp')
BASE_URL = "http://127.0.0.1:8000"
Desire model
from django.db import models
import uuid
from tinymce.models import HTMLField
# Create your models here.
def get_desire_image_filepath(self, filename):
return 'desires/'
def get_default_desire_image():
return "/desires/rope-play.webp"
def get_related_product_image_filepath(self, filename):
return 'related-product/'
def get_default_related_product_image():
return "related-product/swingerprofile.webp"
class Desire(models.Model):
title = models.CharField(max_length=200)
description = models.TextField(null=True, blank=True)
content = HTMLField(null=True, blank=True)
image = models.ImageField(max_length=255, upload_to=get_desire_image_filepath, null=True, blank=True, default=get_default_desire_image)
related_products = models.ManyToManyField('RelatedProduct', blank=True)
def __str__(self):
return self.title
class RelatedProduct(models.Model):
title = models.CharField(max_length=200)
content = HTMLField(null=True, blank=True)
image = models.ImageField(
null=True, blank=True,upload_to='related-product/', default="member/profile/02.jpg")
# image = models.ImageField(max_length=255, upload_to=get_related_product_image_filepath, null=True, blank=True, default=get_default_related_product_image)
redirect_url = models.URLField(max_length=500, null=True, unique=False, blank=True, help_text="The URL to be visited when a notification is clicked.")
def __str__(self):
return self.title
Account model
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
from django.core.files.storage import FileSystemStorage
from django.conf import settings
import os
from django.db.models.signals import post_save
from django.dispatch import receiver
from model_utils import Choices
from friend.models import FriendList
from swinger.models import Swinger
class MyAccountManager(BaseUserManager):
def create_user(self, email, username, couple_choice, password=None):
if not email:
raise ValueError('Users must have an email address')
if not username:
raise ValueError('Users must have a username')
user = self.model(
email=self.normalize_email(email),
username=username,
couple_choice=couple_choice,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, username, password):
user = self.create_user(
email=self.normalize_email(email),
password=password,
username=username,
)
user.is_admin = True
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
return user
def get_profile_image_filepath(self, filename):
return 'profile_images/' str(self.pk) '/profile_image.png'
def get_default_profile_image():
return "profiles/swingerprofile.webp"
class Account(AbstractBaseUser):
COUPLE_CHOICE = Choices('single', 'couple')
email = models.EmailField(verbose_name="email", max_length=60, unique=True)
username = models.CharField(max_length=30, unique=True)
date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True)
last_login = models.DateTimeField(verbose_name='last login', auto_now=True)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
profile_image = models.ImageField(max_length=255, upload_to=get_profile_image_filepath, null=True, blank=True, default=get_default_profile_image)
hide_email = models.BooleanField(default=True)
couple_choice = models.CharField(choices=COUPLE_CHOICE, default='single', max_length=20)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
objects = MyAccountManager()
def __str__(self):
return self.username
def get_profile_image_filename(self):
return str(self.profile_image)[str(self.profile_image).index('profile_images/' str(self.pk) "/"):]
# For checking permissions. to keep it simple all admin have ALL permissons
def has_perm(self, perm, obj=None):
return self.is_admin
# Does this user have permission to view this app? (ALWAYS YES FOR SIMPLICITY)
def has_module_perms(self, app_label):
return True
@receiver(post_save, sender=Account)
def user_save(sender, instance, **kwargs):
FriendList.objects.get_or_create(user=instance)
@receiver(post_save, sender=Account)
def user_save(sender, instance, **kwargs):
Swinger.objects.get_or_create(user=instance)
This is what is show in the source admin page. I think it must be one of these scripts
<!DOCTYPE html>
<html lang="en-us" dir="ltr">
<head>
<title>Test | Change desire | Django site admin</title>
<link rel="stylesheet" type="text/css" href="/static/admin/css/base.css">
<link rel="stylesheet" type="text/css" href="/static/admin/css/nav_sidebar.css">
<script src="/static/admin/js/nav_sidebar.js" defer></script>
<link rel="stylesheet" type="text/css" href="/static/admin/css/forms.css">
<script src="/admin/jsi18n/"></script>
<script src="/static/admin/js/vendor/jquery/jquery.js"></script>
<script src="/static/tinymce/tinymce.min.js"></script>
<script src="/static/admin/js/jquery.init.js"></script>
<script src="/static/django_tinymce/init_tinymce.js"></script>
<script src="/static/admin/js/core.js"></script>
<script src="/static/admin/js/admin/RelatedObjectLookups.js"></script>
<script src="/static/admin/js/actions.js"></script>
<script src="/static/admin/js/urlify.js"></script>
<script src="/static/admin/js/prepopulate.js"></script>
<script src="/static/admin/js/vendor/xregexp/xregexp.js"></script>
<meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1.0, maximum-scale=1.0">
<link rel="stylesheet" type="text/css" href="/static/admin/css/responsive.css">
<meta name="robots" content="NONE,NOARCHIVE">
</head>
<body
data-admin-utc-offset="0">
<!-- Container -->
<div id="container">
<!-- Header -->
<div id="header">
<div id="branding">
<h1 id="site-name"><a href="/admin/">Django administration</a></h1>
</div>
<div id="user-tools">
Welcome,
<strong>wals**.com</strong>.
<a href="/">View site</a> /
<a href="/admin/password_change/">Change password</a> /
<a href="/admin/logout/">Log out</a>
</div>
</div>
<!-- END Header -->
<div >
<a href="/admin/">Home</a>
› <a href="/admin/desire/">Desire</a>
› <a href="/admin/desire/desire/">Desires</a>
› Test
</div>
<div id="main">
<button id="toggle-nav-sidebar" aria-label="Toggle navigation"></button>
<nav id="nav-sidebar">
<div >
<table>
<caption>
<a href="/admin/account/" title="Models in the Account application">Account</a>
</caption>
<tr >
<th scope="row"><a href="/admin/account/account/">Accounts</a></th>
<td><a href="/admin/account/account/add/" >Add</a></td>
</tr>
</table>
</div>
<div >
<table>
<caption>
<a href="/admin/auth/" title="Models in the Authentication and Authorization application">Authentication and Authorization</a>
</caption>
<tr >
<th scope="row"><a href="/admin/auth/group/">Groups</a></th>
<td><a href="/admin/auth/group/add/" >Add</a></td>
</tr>
</table>
</div>
<div >
<table>
<caption>
<a href="/admin/chat/" title="Models in the Chat application">Chat</a>
</caption>
<tr >
<th scope="row"><a href="/admin/chat/privatechatroom/">Private chat rooms</a></th>
<td><a href="/admin/chat/privatechatroom/add/" >Add</a></td>
</tr>
<tr >
<th scope="row"><a href="/admin/chat/roomchatmessage/">Room chat messages</a></th>
<td><a href="/admin/chat/roomchatmessage/add/" >Add</a></td>
</tr>
<tr >
<th scope="row"><a href="/admin/chat/unreadchatroommessages/">Unread chat room messagess</a></th>
<td><a href="/admin/chat/unreadchatroommessages/add/" >Add</a></td>
</tr>
</table>
</div>
<div >
<table>
<caption>
<a href="/admin/desire/" title="Models in the Desire application">Desire</a>
</caption>
<tr >
<th scope="row"><a href="/admin/desire/desire/" aria-current="page">Desires</a></th>
<td><a href="/admin/desire/desire/add/" >Add</a></td>
</tr>
<tr >
<th scope="row"><a href="/admin/desire/relatedproduct/">Related products</a></th>
<td><a href="/admin/desire/relatedproduct/add/" >Add</a></td>
</tr>
</table>
</div>
<div >
<table>
<caption>
<a href="/admin/friend/" title="Models in the Friend application">Friend</a>
</caption>
<tr >
<th scope="row"><a href="/admin/friend/friendlist/">Friend lists</a></th>
<td><a href="/admin/friend/friendlist/add/" >Add</a></td>
</tr>
<tr >
<th scope="row"><a href="/admin/friend/friendrequest/">Friend requests</a></th>
<td><a href="/admin/friend/friendrequest/add/" >Add</a></td>
</tr>
</table>
</div>
<div >
<table>
<caption>
<a href="/admin/notification/" title="Models in the Notification application">Notification</a>
</caption>
<tr >
<th scope="row"><a href="/admin/notification/notification/">Notifications</a></th>
<td><a href="/admin/notification/notification/add/" >Add</a></td>
</tr>
</table>
</div>
<div >
<table>
<caption>
<a href="/admin/public_chat/" title="Models in the Public_Chat application">Public_Chat</a>
</caption>
<tr >
<th scope="row"><a href="/admin/public_chat/publicchatroom/">Public chat rooms</a></th>
<td><a href="/admin/public_chat/publicchatroom/add/" >Add</a></td>
</tr>
<tr >
<th scope="row"><a href="/admin/public_chat/publicroomchatmessage/">Public room chat messages</a></th>
<td><a href="/admin/public_chat/publicroomchatmessage/add/" >Add</a></td>
</tr>
</table>
</div>
<div >
<table>
<caption>
<a href="/admin/swinger/" title="Models in the Swinger application">Swinger</a>
</caption>
<tr >
<th scope="row"><a href="/admin/swinger/swinger/">Swingers</a></th>
<td><a href="/admin/swinger/swinger/add/" >Add</a></td>
</tr>
</table>
</div>
</nav>
<div >
<!-- Content -->
<div id="content" >
<h1>Change desire</h1>
<h2>Test</h2>
<div id="content-main">
<ul >
<li>
<a href="/admin/desire/desire/1/history/" >History</a>
</li>
</ul>
<form enctype="multipart/form-data" method="post" id="desire_form" novalidate><input type="hidden" name="csrfmiddlewaretoken" value="juad4Png7eSuXsum6nCzutBDYsXfvxzVpfcJfwAOnm5LY6WyQMQgf3JyKsFwOKPE">
<div>
<fieldset >
<div >
<div>
<label for="id_title">Title:</label>
<input type="text" name="title" value="Test" maxlength="200" required id="id_title">
</div>
</div>
<div >
<div>
<label for="id_description">Description:</label>
<textarea name="description" cols="40" rows="10" id="id_description">
test desription</textarea>
</div>
</div>
<div >
<div>
<label for="id_content">Content:</label>
<textarea cols="40" data-mce-conf="{"theme": "silver", "height": 500, "menubar": false, "plugins": "advlist,autolink,lists,link,image,charmap,print,preview,anchor,searchreplace,visualblocks,code,fullscreen,insertdatetime,media,table,paste,code,help,wordcount", "toolbar": "undo redo | formatselect | bold italic backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | removeformat | help", "spellchecker_languages": "Afrikaans=af,Arabic / Algerian Arabic=ar,Asturian=as,Azerbaijani=az,Bulgarian=bg,Belarusian=be,Bengali=bn,Breton=br,Bosnian=bs,Catalan=ca,Czech=cs,Welsh=cy,Danish=da,German=de,Lower Sorbian=ds,Greek=el, English / Australian English / British English=en,Esperanto=eo,Spanish / Argentinian Spanish / Colombian Spanish / Mexican Spanish / Nicaraguan Spanish / Venezuelan Spanish=es,Estonian=et,Basque=eu,Persian=fa,Finnish=fi,French=fr,Frisian=fy,Irish=ga,Scottish Gaelic=gd,Galician=gl,Hebrew=he,Hindi=hi,Croatian=hr,Upper Sorbian=hs,Hungarian=hu,Armenian=hy,Interlingua=ia,Indonesian=id,Igbo=ig,Ido=io,Icelandic=is,Italian=it,Japanese=ja,Georgian / Kabyle=ka,Kazakh=kk,Khmer=km,Kannada=kn,Korean=ko,Kyrgyz=ky,Luxembourgish=lb,Lithuanian=lt,Latvian=lv,Macedonian=mk,Malayalam=ml,Mongolian=mn,Marathi=mr,Burmese=my,Norwegian Bokm\u00e5l=nb,Nepali=ne,Dutch=nl,Norwegian Nynorsk=nn,Ossetic=os,Punjabi=pa,Polish=pl,Portuguese / Brazilian Portuguese=pt,Romanian=ro,Russian=ru,Slovak=sk,Slovenian=sl,Albanian=sq,Serbian / Serbian Latin=sr,Swedish=sv,Swahili=sw,Tamil=ta,Telugu=te,Tajik=tg,Thai=th,Turkmen=tk,Turkish=tr,Tatar=tt,Udmurt=ud,Ukrainian=uk,Urdu=ur,Uzbek=uz,Vietnamese=vi,Simplified Chinese / Traditional Chinese=zh", "directionality": "ltr", "mode": "exact", "strict_loading_mode": 1, "elements": "id_content"}" id="id_content" name="content" rows="10"></textarea>
</div>
</div>
<div >
<div>
<label for="id_image">Image:</label>
<input type="file" name="image" accept="image/*" id="id_image"><input type="hidden" name="initial-image" id="initial-id_image">
</div>
</div>
<div >
<div>
<label for="id_image2">Image2:</label>
<input type="file" name="image2" accept="image/*" id="id_image2">
</div>
</div>
<div >
<div>
<label for="id_related_products">Related products:</label>
<div >
<select name="related_products" id="id_related_products" multiple>
<option value="2" selected>Giant Lollipop</option>
</select>
<a id="add_id_related_products"
href="/admin/desire/relatedproduct/add/?_to_field=id&_popup=1"
title="Add another related product"><img src="/static/admin/img/icon-addlink.svg" alt="Add"></a>
</div>
<div >Hold down “Control”, or “Command” on a Mac, to select more than one.</div>
</div>
</div>
</fieldset>
<div >
<input type="submit" value="Save" name="_save">
<p ><a href="/admin/desire/desire/1/delete/" >Delete</a></p>
<input type="submit" value="Save and add another" name="_addanother">
<input type="submit" value="Save and continue editing" name="_continue">
</div>
<script id="django-admin-form-add-constants"
src="/static/admin/js/change_form.js"
async>
</script>
<script id="django-admin-prepopulated-fields-constants"
src="/static/admin/js/prepopulate_init.js"
data-prepopulated-fields="[]">
</script>
</div>
</form></div>
<br >
</div>
<!-- END Content -->
<div id="footer"></div>
</div>
</div>
</div>
<!-- END Container -->
</body>
</html>
CodePudding user response:
just remove self and filename from function.
instead:
def get_desire_image_filepath(self, filename):
return 'desires/'
try this:
def get_desire_image_filepath(instance, filename):
return 'desires/'.format(instance.user.id, filename) #user.id is depends on your view
CodePudding user response:
So after a whole day trying multiple things, it turns out I needed to update chrome!