Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
get the size of an image to be uploaded in django before the upload process starts
Okay, I don't have a code snippet here, I wanted to display a progress bar when I am uploading an image in Django, am using celery and some other stuff, but most importantly i will need to know the size of the file been uploaded so that I can compute the progress of the upload, any suggestion or solutions, please. -
Override a save function to always update or create Django
I want to override the function for saving the profile inside the actual model. Here is my attempt so far: class Profile(models.Model): # others def save(self, *args, **kwargs): # Object is a new profile if email does not exist if not Profile.objects.filter(email = self.email).exists(): # save return super().save(*args, **kwargs) #object is an existing profile else: # update return super().update(*args, **kwargs) Simply update if its on the db. I'm doing this because I can't do the usual update_or_create from ImportExportModelAdmin. Any answer or link is appreciated. -
Exception Type: RelatedObjectDoesNotExist Exception Value: Cart has no owner. Django-eCommerce
I'm trying to make a webshop on Django and im facing up with one problem. When I;m running this code on my PC like python manage.py runserver it works perfect. But when I'm tryieng to run it in my local network like python manage.py runserver 0.0.0.0:8000 then i become this error: RelatedObjectDoesNotExist at /add-to-cart/vw_golf/bags/ Cart has no owner. Request Method: GET Request URL: http://192.168.1.165:8000/add-to-cart/vw_golf/bags/ Django Version: 3.2.4 Exception Type: RelatedObjectDoesNotExist Exception Value: Cart has no owner. Exception Location: C:\Users\dinar\PycharmProjects\shop_scnd_copy\venv\lib\site-packages\django\db\models\fields\related_descriptors.py, line 197, in get Python Executable: C:\Users\dinar\PycharmProjects\shop_scnd_copy\venv\Scripts\python.exe Python Version: 3.9.2 Python Path: ['C:\Users\dinar\PycharmProjects\shop_scnd_copy\venv\django3-ecommerce', 'C:\Users\dinar\AppData\Local\Programs\Python\Python39\python39.zip', 'C:\Users\dinar\AppData\Local\Programs\Python\Python39\DLLs', 'C:\Users\dinar\AppData\Local\Programs\Python\Python39\lib', 'C:\Users\dinar\AppData\Local\Programs\Python\Python39', 'C:\Users\dinar\PycharmProjects\shop_scnd_copy\venv', 'C:\Users\dinar\PycharmProjects\shop_scnd_copy\venv\lib\site-packages'] These are my classes Cart and Customer: class Cart(models.Model): owner = models.ForeignKey('Customer', verbose_name='Kunde', on_delete=models.CASCADE) products = models.ManyToManyField(CartProduct, blank=True, related_name='related_cart') total_products = models.PositiveIntegerField(default=0) final_price = models.DecimalField(max_digits=9, default=0, decimal_places=2, verbose_name='Gesamtpreis') in_order = models.BooleanField(default=False) for_anonymous_user = models.BooleanField(default=False) def __str__(self): return str(self.id) class Customer(models.Model): user = models.ForeignKey(User, verbose_name='Kunde', on_delete=models.CASCADE) phone = models.CharField(max_length=20, verbose_name='Handynummer', null=True, blank=True) email = models.EmailField(max_length=255, verbose_name='Email', default='') address = models.CharField(max_length=255, verbose_name='Adresse', null=True, blank=True) orders = models.ManyToManyField('Order', verbose_name='Bestellungen', related_name='related_order') def __str__(self): return "Kunde: {} {}".format(self.user.first_name, self.user.last_name) This is my view: class AddToCartView(CartMixin, View): def get(self, request, *args, **kwargs): ct_model, product_slug = kwargs.get('ct_model'), kwargs.get('slug') content_type = ContentType.objects.get(model=ct_model) product = content_type.model_class().objects.get(slug=product_slug) cart_product, created = CartProduct.objects.get_or_create( user=self.cart.owner, … -
Returning the first object in a django queryset
I want to grab only the first element in the queryset below. But if add .first(), it returns an error saying that 'Product' object is not iterable query = Product.objects.filter(user=request.user).order_by('-created_at') Since this is not iterable, how can I grab the first object without converting to other datatypes like list -
python – My django’s website on cpanel doesn’t load my media files but all my stacticfiles and media work when DEBUG= True
i need some help to display my media files when debug= False I have a Django project that is working fine and showing all media files downloaded from admin when debug = True but I immediately change debug = False Django can't find my media folder but it loads my static folder. as you can see i have correctly configured my MEDIA_ROOT and MEDIA_URL. this is my setting.py setting.py import os from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = '#############################' DEBUG = False ALLOWED_HOSTS = ['##############################'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'appsolve.apps.AppsolveConfig', 'ACCOUNTS', 'afiilitePrograme', 'manageapps', 'News', 'contactUS', ] MIDDLEWARE = [ 'whitenoise.middleware.WhiteNoiseMiddleware', #'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware',**strong text** 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'alpha1.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['alpha1/templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'alpha1.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True MEDIA_URL = '/media/' STATIC_URL = '/static/' STATIC_ROOT='collected/static' MEDIA_ROOT … -
I want to display another model in the home admin site page django
In the admin site I display custom users, I mean in admin.py I wrote from .models import User, Product, Address from django.contrib import admin from .forms import CustomUserCreationForm from django.contrib.auth.admin import UserAdmin class CustomUserAdmin(UserAdmin): model = User add_form = CustomUserCreationForm fieldsets = ( *UserAdmin.fieldsets, ( 'Additional fields:', { 'fields': ( 'phone_number', 'billing_address', 'shipping_address', ) } ) ) admin.site.register(User, CustomUserAdmin) User is my model that inherits from AbstractUser, I want to display another model too which is called Product. How to do that? Here it is the second model class Product(models.Model): name = models.CharField(max_length=50) SKU = models.CharField(max_length=50) description = models.CharField(max_length=300) price = MoneyField(max_digits=19,decimal_places=4,default_currency='USD') class Product(models.Model): name = models.CharField(max_length=50) SKU = models.CharField(max_length=50) description = models.CharField(max_length=300) price = MoneyField(max_digits=19,decimal_places=4,default_currency='USD') class ProductImage(models.Model): product = models.ForeignKey(Product, related_name='images', on_delete=models.RESTRICT, null=True) image = models.ImageField() -
django page load slow in 10 seconds
The page is loading in 10 seconds and after downloading django-debug-toolbar i saw that I am making 124 queries and 90% of them are duplicates. class TerminalManagementView(LoginRequiredMixin, TemplateView): template_name = "app/terminal_management.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['tb_terminal_categories'] = TbTerminalCategory.objects.all() context['tb_terminal_caregory_form'] = TbTerminalCategoryForm() context['tb_terminal_register_form'] = TbTerminalRegisterForm() filter = self.request.GET.get('category') if filter: terminals = TbTerminal.objects.all().filter( category__category_name=filter).order_by('create_time') else: terminals = TbTerminal.objects.all().order_by('create_time') page = self.request.GET.get('page', 1) paginator = Paginator(terminals, 9) try: data = paginator.page(page) except PageNotAnInteger: data = paginator.page(1) except EmptyPage: data = paginator.page(paginator.num_pages) context['terminals'] = data return context in this model I reference 4 other models, how do make this implementation work faster? class TbTerminal(models.Model): id = models.CharField(primary_key=True, max_length=32, default=generate_uuid) customer = models.ForeignKey( TbCustomer, on_delete=models.CASCADE, db_column='cstm_id') terminal_id = models.CharField(max_length=64, blank=True, null=True) area = models.ForeignKey( TbArea, on_delete=models.CASCADE, db_column='extra_id1') room = models.ForeignKey( TbRoom, on_delete=models.CASCADE, db_column='extra_id2') terminal_name = models.CharField(max_length=64, blank=True, null=True) terminal_desc = models.CharField(max_length=255, blank=True, null=True) category = models.ForeignKey( TbTerminalCategory, on_delete=models.CASCADE, db_column='cat_id') device_model = models.ForeignKey( TbDeviceModel, on_delete=models.CASCADE, db_column='device_model_id') -
How to store a dictionary in a Django database model's field?
I want to store this list of dictionarys in a Django database: h = [ {'sale_id': 14, 'name': 'Macarena', 'fecha': datetime.date(2021, 3, 11), 'debe': 500.0}, {'sale_id': 14, 'name': 'Macarena', 'fecha': datetime.date(2021, 4, 11), 'debe': 500.0}, {'sale_id': 15, 'name': 'Yamila', 'fecha': datetime.date(2021, 4, 14), 'debe': 2000.0} ] I've tried this: h = tabla_creditos() class Creditos1(models.Model): sale_id = models.IntegerField(default=0) name = models.CharField(max_length=150) fecha = models.DateTimeField(default=datetime.now) debe = models.IntegerField(default=0) for i in range(0,len(h)): Creditos1.objects.create(name=h[i]['name'], sale_id=h[i]['sale_id'], fecha=h[i]['fecha'], debe=h[i]['debe']) where "h" is that dictionary, which results from "tabla_creditos()" function. And then, I tried to create the values for the DB with "objects.create" but I got duplicated values stored in DB: So, how can I store that dict in the DB? I found this solution: How to store a dictionary in a Django database model's field but none of the answers helped me. Thanks! -
How to change django-phonenumber-field error messages
I am using django-phonenumber-field. Everyone who uses this app probably knows that any prefix has the same example "Enter a valid phone number (e.g. +12125552368)." Enter a valid phone number (e.g. +12125552368). So, I don't like it and I wanted to change it but I could not change this text, I thought I would change it in html like this: {% if form.phone.errors %} <p class="alert-p"></p>Incorrect International Calling Code or Mobile Number!</p> {% endif %} Incorrect International Calling Code or Mobile Number! But when I changed it I realized that this method would not work for me because there was a likelihood that users would enter the same phone number and could not understand why it would not save if it did not send the appropriate error message. (phone number is unique) Now there is a problem, in one case, when the user enters the wrong number in the prefix, this time I want my built-in text to drop out as an error message, but when users enter the same number I want to drop out the django-phonenumber-field default Error message Account with this Phone already exists. I will take any advice on how I can solve this problem. -
Django ORM - Email groups
I'm try make a email group model in django that has "recipient" & "copy" fields. How can I do this? if you have a better implementation suggestion than below, pls let me know! from django.db import models class Email(models.Model): email_id = models.AutoField(primary_key = True) recipient = models.EmailField(unique=True, null=True) copy = models.EmailField(unique=True, null=True) def __str__(self): return self.recipient +" - "+ self.copy class EmailGroup(models.Model): group_id = models.AutoField(primary_key = True) group_name = models.CharField(max_length=50) sector = models.CharField(max_length=50) recipient = models.ManyToManyField(Email) copy = models.ManyToManyField(Email) def __str__(self): return self.group_name +" - "+ self.sector -
Send scheduled email django
I have made a small django app to fit all my needs. I will use it on my company level to track simple tasks of couple mehanical engineers. Now, only thing left is to send scheduled emails (every day at noon, if someone is behind with work, he would get an email). Since I'm using Windows and I'll deploy this app on Windows, I can't use cron job (this only works on Linux, as I've seen on forums), which is simple and easy. Only way I found so far was using django-celery-beat. This is not so easy to set up, and I need to run 'worker' each time I run my server. This is a bit above my level and I would need to learn a lot more (and it needs to have a message broker, like RabbitMQ, which I also need to run and learn to implement). I was wondering is there a more easy way to send a simple email every day at noon? I don't want to install additional apps, I wish to keep it simple as possible. -
Problem with Data Baze Sqlite in python django
I asked this but nobody help me. Because I try ask it again. Situation: I have a VPS server (OS: Ubuntu). I have to create a site on python django. I don't have a problem with it. Problem become when I create a project. Django project was generated. I did a migration. But when I log in super user menu this error show up: OperationalError at /admin/login/ attempt to write a readonly database I tried find a answer. Someone wrote that I need to give a grant to write in sqlite. I used putty and wrote mysql then CREATE USER 'novyi_polzovatel'@'localhost' IDENTIFIED BY 'parol'; and GRANT ALL PRIVILEGES ON * . * TO 'novyi_polzovatel'@'localhost'; But console show an error with syntax Before I don't have this problem Please help And sorry for my English -
File not automatically downloading
Hi there i have a view function which gives a response in a csv file but when i call it using the Django Api view it gives or shows nothing and not even starts downloading, here is my code @api_view(['POST']) @authentication_classes([SessionAuthentication, BasicAuthentication, TokenAuthentication]) u/permission_classes([IsAuthenticated]) def attendance_datasetgenerator(request): serializer = DatasetGeneratorSerializer(request.data) start_roll = serializer.data['start_roll'] end_roll = serializer.data['end_roll'] start_date = serializer.data['start_date'] end_date = serializer.data['end_date'] subject = serializer.data['subject'] att= Attendance.objects.filter(date__range=(start_date,end_date), student__pk__range=(start_roll,end_roll), subject__exact=subject) att2= Attendance.objects.exclude(date__range=(start_date,end_date), student__pk__range=(start_roll,end_roll), subject__exact=subject) df2 = DataFrame(att2.values()) df1 = DataFrame(att.values()) csv1 = df1.to_csv() csv2 = df2.to_csv() file1 = StringIO() file1.write(csv1) response = HttpResponse(file1, content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=file1.zip' return response kindly guide -
Django Haystack can't update indexes when I insert a new record
I use haystack (whoosh) in my Django project and I set HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor' to update indexes when I insert a new record. It work well on my pc. I have a cloud server and I use docker-compose to deploy my project. At this time, this feature no longer works. Has anyone encountered a similar problem, how can I solve it? Thank for your reply firstly !! -
GET js chunk 404'd on all but one chunk
I'm running a react frontend with django backend on aws lightsail (bitnami apache server). Everything had been working fine until I changed some frontend code and reran npm run build on the server. It completed successfully and I see the chunks in the correct static folder. All of them are there. When I access the website, it loads one of the chunks and then 404's on the rest. The built css chunks are all there, too. I've restarted the apache server a couple times for good measure but have the same problem. Any idea what could be happening? -
RuntimeWarning: DateTimeField (unbound) received a naive datetime , when increment duration until datetime.now
I'm trying to increment a duration until a condition. Data is saved in database but page doesn't refresh and I'm getting this error. What can be done? RuntimeWarning: DateTimeField (unbound) received a naive datetime (2021-07-04 18:54:38.827527) while time zone support is active. warnings.warn("DateTimeField %s received a naive datetime (%s)" I'm using this code in my views from datetime import datetime ... if form.is_valid(): numof=form.cleaned_data['Numero_Of'] QuerySet_of=OF.objects.get(Numero_Of=numof) Usin=Poste.objects.get(OF_id=QuerySet_of.Id_OF,Nom_poste__startswith = "MGP") while Usin.Date_S_poste is None : OF.objects.filter(Id_OF=QuerySet_of.Id_OF).update(Nb_jrs_att_Usin = datetime.now() - F('Date_E_initial')) models.py Nb_jrs_att_Usin=models.DurationField(null=True, blank=True) In my settings, I have changed TIME_ZONE to TIME_ZONE = 'Africa/Tunis' USE_I18N = True USE_L10N = False USE_TZ = True -
How to view slideshow in django?
I am building a side project in Django where I have the following feature. There is a list of projects which a name and 10 images associated to it. When the user clicks on the name, there should be a pop up, having the slideshow of all the images associated to that particular project. I am using plain HTML for the templates along with the Django templating language. Can someone please help me out in doing this? My models.py is like class Project(models.Model): project_id = models.AutoField project_name = models.CharField(max_length=100, blank=False) project_img1 = models.ImageField( upload_to='project_images', blank=True, null=True) project_img2 = models.ImageField( upload_to='project_images', blank=True, null=True) project_img3 = models.ImageField( upload_to='project_images', blank=True, null=True) project_img4 = models.ImageField( upload_to='project_images', blank=True, null=True) project_img5 = models.ImageField( upload_to='project_images', blank=True, null=True) project_img6 = models.ImageField( upload_to='project_images', blank=True, null=True) project_img7 = models.ImageField( upload_to='project_images', blank=True, null=True) project_img8 = models.ImageField( upload_to='project_images', blank=True, null=True) project_img9 = models.ImageField( upload_to='project_images', blank=True, null=True) project_img10 = models.ImageField( upload_to='project_images', blank=True, null=True) def __str__(self): return self.project_name PS: The url remains same. It's just a pop-up/modal that opens/closes on button click. I am doing so by using the display:none property in CSS. -
Cheaper api alternatives for Twilio [closed]
Is there any cheaper alternative for Twilio in India? I am currently working on a Django project and I want to add a feature to make calls within my app. Initially I go for the Twilio API, but it is too expensive, and I can't afford that. -
I'm using pinax-referral but when I follow through I'm getting raise.self.model.DoesNotExist and also Value error for unable to configure logger
I'm trying to use pinax-referral but when I follow through I'm getting raise.self.model.DoesNotExist and also Value error for unable to configure logger This my logger that its triggering the ValueError: Unable to configure handler 'debug' LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'simple': { 'format': '[%(asctime)s] | %(levelname)s | %(message)s', 'datefmt': '%d/%b/%Y %H:%M:%S', }, }, 'handlers': { 'debug': { 'level': 'DEBUG', 'class': 'logging.handlers.RotatingFileHandler', 'filename': 'logging/debug.log', 'maxBytes': 1024*1024*5, 'formatter': 'simple', }, 'error': { 'level': 'ERROR', 'class': 'logging.handlers.RotatingFileHandler', 'filename': 'logging/error.log', 'maxBytes': 1024*1024*5, 'formatter': 'simple', }, }, 'loggers': { 'django': { 'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'), 'handlers': ['debug', 'error'], }, }, } the other issue its saying raise self.model.DoesNotExist( App1.models.Profile.DoesNotExist: Profile matching query does not exist. and when I counter check I find this File "C:\Users\n\PycharmProjects\Elijahs_Agnes\App1\views.py", line 76, in get_context_data profile = Profile.objects.get(user=self.request.user) this the part class DashboardView(TemplateView): template_name = "dashboard.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # Current user context['user'] = self.request.user # The user who brought the current user to the system profile = Profile.objects.get(user=self.request.user) if profile.parent: context['parent'] = profile.parent.user parent_amount = (int(PRICE) * 5) / 100 else: context['parent'] = None parent_amount = 0 -
Asyncwebsocketconsumer disconnect methods runs after some delay
I am running into a major issue while working on a app. The issue is that when the user loses internet connection the disconnect method of asyncwebsocketconsumer is expected to run. It does run but after some delay of around 10-15 seconds. Is there any way to reduce this delay? -
Django Using oembed to convert url to embed url(VIMEO)
I try to convert video url to embed url... with using oEmbed But enter image description here When I print(video_url_api_data) it keep returning <Response [404]> I checked it with using url in google https://vimeo.com/api/oembed.json?url=https://vimeo.com/570924262 What did i do wrong with my code? and What am i have to put at the status part( vimeo_authorization_url = v.auth_url( ['private'], 'http://127.0.0.1:8000/', 1 #status ) this status part! I put 1 for random... and it works.. in advance import json, vimeo, requests class article_upload(View): def post(self ,request, *args, **kwargs): v = vimeo.VimeoClient( token='****', key='****', secret='****' ) file_data = request.FILES["file_data"] path = file_data.temporary_file_path() try: vimeo_authorization_url = v.auth_url( ['private'], 'http://127.0.0.1:8000/', 1 #status ) video_uri = v.upload(path, data={'name': '비디오 제목', 'description': '설명'}) video_data = v.get(video_uri + '?fields=link').json() video_url = video_data['link'] params={"url": video_url} video_url_api_data = requests.get('https://vimeo.com/api/oembed.json', params=params) return render(request, 'account/myvideopage.html', {context(I made it)}) except vimeo.exceptions.VideoUploadFailure as e: print("ohohohohohoh...vimeo error") finally: file_data.close() # Theoretically this should remove the file if os.path.exists(path): os.unlink(path) # But this will do it, barring permissions -
pip install virtualenv error python django
WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(<pip._vendor.urllib3.connection.HTTPSConnection object at 0x00000000048A65E0>, 'Connection to 10.8.0.1 timed out. (connect timeout=15)')': /simple/virtualenv/ WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(<pip._vendor.urllib3.connection.HTTPSConnection object at 0x00000000048A6610>, 'Connection to 10.8.0.1 timed out. (connect timeout=15)')': /simple/virtualenv/ WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(<pip._vendor.urllib3.connection.HTTPSConnection object at 0x00000000048A6460>, 'Connection to 10.8.0.1 timed out. (connect timeout=15)')': /simple/virtualenv/ WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(<pip._vendor.urllib3.connection.HTTPSConnection object at 0x00000000048A62E0>, 'Connection to 10.8.0.1 timed out. (connect timeout=15)')': /simple/virtualenv/ WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(<pip._vendor.urllib3.connection.HTTPSConnection object at 0x00000000048A60A0>, 'Connection to 10.8.0.1 timed out. (connect timeout=15)')': /simple/virtualenv/ -
is there a way to generate unique payment urls for each customers in python api using stripe? [closed]
I need to generate unique payment urls which will be forwarded to the customer ,through which customer can pay the amount in stripe. I would like to implement this in python django. -
How do you add Vue to Django?
I'm am trying to add a reactive Vue js on the frontend and have Django serve the different pages on the backend. But how do you add these guys together?? I have found different ways to do so, but I can't find a good explanation on the why they are tying them together that way. I was hoping for a comprehensive explanation as to how these 2 are added together but also the why? I am still new to both of these frameworks so I am trying to understand not only how to do something but the reason for my doing them. Thanks in advance. -
Slug filed is not showing in Django Admin
I am working on a Django application, In my models, I have a product class with SlugField but it is not showing in Django Admin Panel. class Product(models.Model): name = models.CharField(max_length=200) slug = models.SlugField(max_length=200, unique=True), price = models.DecimalField(max_digits=6, decimal_places=2) description = models.TextField() image = models.ImageField(upload_to=product_directory_path, blank=True) featured = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) category = models.ForeignKey( Category, blank=True, null=True, on_delete=models.CASCADE) def __str__(self): return self.name class Meta: ordering = ('name',) @admin.register(Product) class ProductAdmin(admin.ModelAdmin): prepopulated_fields = {'slug': ('name',)} [![enter image description here][1]][1] when I am adding prepopulated fields in admin.py it is showing me this error. ERRORS: <class 'shop.admin.ProductAdmin'>: (admin.E027) The value of 'prepopulated_fields' refers to 'slug', which is not an attribute of 'shop.Product'. I have tried migrations but it tells me 'No Changes detected'. The below Image shows that Django Admin isn't detecting my slug field. Image