Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
No 'Access-Control-Allow-Origin' header is present on the requested resource.
I am using ajax to call the following url: "https://www.bittrex.com/api/v1.1/public/getticker?market=usdt-btc" I am getting the following error: No 'Access-Control-Allow-Origin' header is present on the requested resource. I have installed django-cors-headers and my settings.py looks like this: INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'crispy_forms', # The following apps are required: 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) CORS_ORIGIN_ALLOW_ALL = True CORS_ORIGIN_WHITELIST = ( 'http://127.0.0.1:8000', ) Why am I still getting the error? ** I have read all the other answers related to this but they have not helped me. I have used the chrome plugin too and it does work with it but I want a solution without it ** Django Version = 1.8 -
How to update django model fields without knowing which fields to be updated beforehand?
I want to update a model without knowing which fields to update beforehand. For example: The request to my url api/user/(?P<pk>[0-9]+)/message-update/(?P<id>[0-9]+)/ will have a payload JSON with a POST request method like this: { "category": "personal", "type_of_transaction": "paid" } The problem here is that the payload key-value pairs will keep changing depending upon the fields to be changed. I have tried this but it seems to have no effect at all: message = Message.objects.get(user=pk, id=id) json_data = json.loads(request.body.decode(encoding='UTF-8')) attributes_to_be_changed = json_data.keys() values = json_data.values() for i in attributes_to_be_changed: message.i = values[attributes_to_be_changed.index(i)] message.save(update_fields=attributes_to_be_changed) try: json_message = MessageSerializer(Message, many=False) except Exception as e: return JsonResponse({"error": e}) return JsonResponse(json_message.data, safe=False) I have a message model as below: user = models.ForeignKey(User, related_name='messages') sender = models.CharField(max_length=15, blank=True) body = models.CharField(max_length=400, blank=True) account = models.ForeignKey(Account, blank=True, null=True) card = models.ForeignKey(CreditCard, blank=True, null=True) type_of_transaction = models.CharField(max_length=10) message_date = models.DateTimeField(blank=True, null=True) category = models.CharField(max_length=15, blank=True) spent_at = models.CharField(max_length=15, blank=True) meta = models.CharField(max_length=30, blank=True) amount = models.FloatField() lat = models.CharField(max_length=50, default="null") lon = models.CharField(max_length=50, default="null") def __str__(self): try: state = "Message from "+self.account.name+" for "+self.user.username except Exception: state = "Message from "+ self.card.card_number+"for"+self.user.username return state -
./manage.py shell deletes the contents of the file
In my Django project I have a couple of methods I manually call time to time for testing purposes, but lately something strange is happening. Whenever I try to run a function in the context of my Django app: ./manage.py shell > scraper/update_db.py it overwrites the contents of "update_db.py" with this: >>> I've tried creating arbitrary python files with simple print statements, but same happens to all of them. My current update_db.py looks like this: def consistency_check(): # removed my code with print statement print('Hello') consistency_check() Any ideas what is happening? I guess it's worth mentioning that I'm working in Pycharm and when I import my functions in python console, it's working just fine in there: from scraper import update_db update_db.consistency_check() # Runs smoothly -
Custom Data Model in Django
Problem: A company has to work with different forms of automobiles like car, truck, bus etc. Primary Goal: Implement a solution that allows users to define their own custom data model for their automobiles. There should be no database tables called car, truck, or bus. Instead, users should be able to create their own automobiles types and attach as many different fields as they would like. Data: For the data layer, model the automobiles types and how the generic fields and field types would relate to these automobiles types. Field types should be either text, number, date, or enum. Backend: Create two API endpoints. One that returns a single automobile type and one that returns a list of all automobiles types. Include all of the automobiles type's fields, field types, and any other data about the fields. How do I achieve this functionality using Django and any JavaScript Framework (AngularJS or ReactJS)? My question here is that: How to provide a form in JavaScript where the user can add these custom fields and then save these fields in Django? -
How to use django-markdownx in my view in similar way to admin?
I'm stuck using django-markdownx to automatically update page and to submit changes. I followed this question and answer and managed to get django-markdownx working in admin, and within my view. However in my view editing the textarea does not automatically update the page. The admin page with django-markdownx is exactly what I want, updating the textarea updates the page, but not the underlying database field until you hit save. So I then tried to rip out the admin code into my own view. In my view/template I have a form, textarea similar to admin one. I also included "/static/markdownx/js/markdownx.js" and set my form to mostly be similar to the admin page: <form method="POST" action="">{% csrf_token %} <div class="markdownx"> <textarea name="myfield" rows="10" cols="40" required="" data-markdownx-upload-urls-path="/markdownx/upload/" data-markdownx-editor-resizable="" class="markdownx-editor" id="id_myfield" data-markdownx-urls-path="/markdownx/markdownify/" data-markdownx-latency="500" data-markdownx-init="" style="transition: opacity 1s ease;"> {{ note.myfield }} </textarea> </div> <div class="markdownx-preview"> {{ note.formatted_markdown|safe }} </div> </form> This didn't work. I see periodically there is requests to /markdownx/markdownify/ when you edit in admin, but not mine. I'm not sure if I should aim to do the same or just do some timed javascript page refresh and pass all the data from within my form back to my view to then re-render … -
Django admin site lost all its formatting
I change my computer and I migrated my django project just by copying the directory created by django-admin create project from the old computer to the new one. I installed all required modules in the new computer (including django) under a new Python virtual environment, and everything worked perfectly, but the admin site of the project, that shows in plain html with no styling at all. I don't know how to fix it -
load language file temporarily for specific purpose only
I am using gettext(), which works very fine depending on the logged in user's preference. Currently, there are French and English languages. THe app is django 1.11 with python 3.4 Now, an English is loaded for user A. But he wants to send a predefined message to User B, who has indicated French as his preferred language. Without reloading the loaded language, is there a simple way to load the french language for that specific task, get the required message by its msgid and destroy it from memory? The current solution in the existing system is to read Json files for such tasks. But I am looking forward to have one language file for each language (.po) instead of Json and po files. -
Materialize css 'select' not working with django
I have this template that collects all names of authors from author_info model. These names are shown as a drop down list. When i pass the selected value to the view, it shows null. The template: <select> <option value="" disabled selected>Choose author</option> {% for author in ainfo %} <option value="{{author.name}}" name="author_name">{{author.name}}</option> {% endfor %} </select> The code snippet from views: if request.method=="POST": author=request.POST.get('author_name') -
Signup email validation using Django rest framework
I am creating a user by sending a POST request through an android app with the request containing a username, password, and email-id. Now in my app, there are two kinds of users i.e. Teachers and Students. Now for distinguishing between teachers and students during signup I want to send a verification email to the teacher comprising of a randomly generated token. Now I want the teacher to enter this token during the signup to verify that actually, a teacher is signing up and not some mischievous student who just wants to mess up with everyone. I am able to send email containing a token but cannot understand that how will I verify it when the teacher enters the token on the app while signing up, matches with the token sent to the email-id. Below is the code of my serializer used to send the email containing a token class UserSerializer(serializers.ModelSerializer): token = serializers.CharField(max_length=100, null=True, blank=True) class Meta: model = User fields = ('id', 'username', 'password', 'email', 'token') def create(self, validated_data): user = User(username=validated_data['username'], email=validated_data['email']) user.set_password(validated_data['password']) user.save() subject = "Email verification for django" message = account_activation_token.make_token(user) send_mail(subject, message, settings.EMAIL_HOST_USER, [user.email]) return user As you peeps can see, in the above … -
migrate from python-social-auth to Django rest-framework Social Oauth2
I have a working app using python-social-auth. I want to support a new app that we are building with ReactJs to use our django backend with django-rest-framework-social-oauth2 Currently, I am using @staff_member_required decorator around my views manually like this: @staff_member_required def index(request): do_something() and if the user is not logged in, it redirects him to login/google-oauth2. The current SETTINGS.py includes: SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = "my_key" SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = "my_secret" LOGIN_URL = "/login/google-oauth2/" LOGIN_REDIRECT_URL = "/" SOCIAL_AUTH_LOGIN_REDIRECT_URL = "/" SOCIAL_AUTH_GOOGLE_OAUTH2_WHITELISTED_DOMAINS = ["my_domain.com"] In order to migrate to django-rest-framework-social-oauth2 I modified the code to be: "context_processors": [ "social_django.context_processors.backends", "social_django.context_processors.login_redirect", ... ] INSTALLED_APPS = ( .... "oauth2_provider", "social_django", "rest_framework_social_oauth2", ) AUTHENTICATION_BACKENDS = ( "social_core.backends.google.GoogleOAuth2", "rest_framework_social_oauth2.backends.DjangoOAuth2" "django.contrib.auth.backends.ModelBackend", ) However, I am not sure how to make the @staff-member_required decorator work with django-rest-framework-social-oauth2 - since now, I would like it to be able to accept also a token like this: curl -H "Authorization: Bearer google google_token" http://localhost:8000/route/to/your/view In addition, what is the URL that I need to forward my users if they are not login if they are trying to log with my existing django app? after my change from python-social-auth (which worked with login/google) to django-rest-framework-social-oauth2 the url /login/google-oauth2/ returns page not found. -
Django sql query
I understand that there is an option to write directly queries in SQL when write in Django... I do not understand why use it and how? maybe example will help -
AttributeError: 'module' object has no attribute 'lru_cache'
Im getting the error as shown in title with this environment setup. Apache2 with mod_wsgi ,Python 3.5, Django 2.0.2 . I'm using virtualevn. my virtual env is in : /home/santosh/Documents/project/project/ and django app is in /home/santosh/Documents/project/Reports Below is the content of wsgi.py file import os, sys sys.path.append('/home/santosh/Documents/project/Reports/Reports') sys.path.append('/home/santosh/Documents/project/Reports') add the virtualenv site-packages path to the sys.path sys.path.append('/home/santosh/Documents/project/project/lib/python3.5/site-packages') sys.path.append('/home/santosh/Documents/project/project/lib/python3.5') sys.path.append('/home/santosh/Documents/project/project/bin') from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Reports.settings") application = get_wsgi_application() Stacktrace: [Sun Feb 04 20:40:39.396427 2018] [wsgi:error] [pid 6428:tid 140043928524544] [client 127.0.0.1:60276] mod_wsgi (pid=6428): Target WSGI script '/home/santosh/Documents/project/Reports/Reports/wsgi.py' cannot be loaded as Python module. [Sun Feb 04 20:40:39.398284 2018] [wsgi:error] [pid 6428:tid 140043928524544] [client 127.0.0.1:60276] mod_wsgi (pid=6428): Exception occurred processing WSGI script '/home/santosh/Documents/project/Reports/Reports/wsgi.py'. [Sun Feb 04 20:40:39.398425 2018] [wsgi:error] [pid 6428:tid 140043928524544] [client 127.0.0.1:60276] Traceback (most recent call last): [Sun Feb 04 20:40:39.398475 2018] [wsgi:error] [pid 6428:tid 140043928524544] [client 127.0.0.1:60276] File "/home/santosh/Documents/project/Reports/Reports/wsgi.py", line 30, in [Sun Feb 04 20:40:39.398555 2018] [wsgi:error] [pid 6428:tid 140043928524544] [client 127.0.0.1:60276] from django.core.wsgi import get_wsgi_application [Sun Feb 04 20:40:39.398565 2018] [wsgi:error] [pid 6428:tid 140043928524544] [client 127.0.0.1:60276] File "/home/santosh/Documents/project/project/lib/python3.5/site-packages/django/init.py", line 1, in [Sun Feb 04 20:40:39.398591 2018] [wsgi:error] [pid 6428:tid 140043928524544] [client 127.0.0.1:60276] from django.utils.version import get_version [Sun Feb 04 20:40:39.398598 2018] [wsgi:error] [pid 6428:tid 140043928524544] [client 127.0.0.1:60276] … -
Image loading fails for Firefox but runs fine for Chrome and IE
I wrote a django app that gets the info of a Twitter account and display it's profile image on a web page. While doing this I noticed that whenever I load the page where the image is present, Firefox does not load the image (the image loads perfectly on Chrome and Edge), it doesn't even seem to try (as there is no log in the network tab of page inspector). I tested it to check if it's Twitter who is blocking people from loading their stuff in other sites by putting a simple <img src="https://pbs.twimg.com/profile_images/953783329093967872/Dn_-PaQA.jpg"> tag in a new html file and run it across all browser on my system. The result is good, all browsers display the image correctly. I tested it again by running the app and load the page but it doesn't load the image on Firefox (loads perfectly on Chrome and Edge) but when I replace the src url with a url of another image on imgur and it displays it properly on Firefox (loads perfectly on Chrome and Edge). I also tried it using an image from another profile and that failed as well on Firefox. It seems that the image can't be loaded only … -
Django NameError - Name 's' is not defined
Amateur Developer, I have the following code that worked fine in Python 2.7, Django 1.10. But now as I upgraded to Django 2+ and Python 3+ it gives an error. View code: def get_class_name(request): class_name = ClassName.objects.get(pk = request.GET.get('class_name', None)) classes = Class.objects.filter(class_name = class_name) l = [[", ".join([s.subject for s in x.subject.all()]),s.id] for x in classes] The error message: NameError at /ajax/get_class_name/ name 's' is not defined Request Method: GET Request URL: http://localhost:8000/ajax/get_class_name/?class_name=1 Django Version: 2.0 Exception Type: NameError Exception Value: name 's' is not defined Model: class Class(models.Model): subject = models.ManyToManyField(Subject) How do I fix it? -
time difference with F experession: error
When I try to calculate a time difference between two fields using F expression it results in TypeError. I can't understand what's the problem, especially because there are other examples where F expressions were used to do the same (here: Timedelta between two fields) model: class TimeStamp(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) Expression: q = TimeStamp.objects.all().annotate(diff=F('created_at')-F('updated_at')) print(q) and error reports (not a full report): File "lib/python3.5/site-packages/django/utils/dateparse.py", line 93, in parse_datetime match = datetime_re.match(value) TypeError: expected string or bytes-like object I use Django 1.8.8 if this matters. -
Why does django inside a container needs the "it" flag?
I try to run django on a docker container using sqllite as the db and the django dev server. So far I was able to launch locally the django server : "python .\manage.py runserver". I can build the docker image [https://github.com/RemiBou/Pithocker/blob/master/DockerFile] : "docker build . -t pythocker" But when I run the image with "docker run -p 8000:8000 pythocker" no output is shown and the machine is not reachable, I have to kill the running container. If I add the "-it" flag on the "docker run" command then the server is running and I can go to "http://192.168.99.100:8000" and display the django welcome page. Wy is thhis flag mandatory here ? Docker logs on the container gives nothing. I also tryed to add custom logging inside the manage.py but it's still not diplayed or in the docker logs. I am using the Docker Windows toolbox as I have only a windows home computer. -
Django attribute error 'LinkWidget' object has no attribute 'template_name' with django-filter and django>=1.11
My Django project throws an attribute error after upgrading Django from 1.10.8 to 1.11(.x). I'm using django-filter with the LinkWidget. The error only occurs when using the LinkWidget and only with Django>=1.11: # filters.py class PostFilter(django_filters.FilterSet): post_type = django_filters.ChoiceFilter( choices=PostPage.POST_TYPE_FILTER_CHOICES, label="Type", widget=LinkWidget() ) class Meta: model = PostPage fields = ['post_type', 'categories'] AttributeError at /articles/ 'LinkWidget' object has no attribute 'template_name' Request Method: GET Request URL: http://127.0.0.1:8000/articles/ Django Version: 1.11 Exception Type: AttributeError Exception Value: 'LinkWidget' object has no attribute 'template_name' Exception Location: /home/tombreit/projects/giz-sta/giz-sta-cop/venv/lib/python3.5/site-packages/django/forms/widgets.py in get_context, line 212 Python Executable: /home/tombreit/projects/giz-sta/giz-sta-cop/venv/bin/python Full traceback: http://dpaste.com/20H1DHP I've read the Django 1.11 Release Notes and found some references regarding template based widget rendering, but can not see how this is related to my django-filter implementation - and it seems that I am the only one with this error which is perplexing... What am I doing wrong? Setup: Django (1.11.10) django-filter (1.1.0) Python 3.5.3 -
Handle Facebook Deauthorize Callback in Python
I am building a Django Application that makes use of the Facebook Login using django-allauth. I would like to know when an user removes my corresponding Facebook App, and Facebook provides such functionality in the form of a deauthorize callback. There are also some instructions on how to parse the request using PHP in the documentation. However, translating this into Python doesn't seem to be as easy as I thought, as I am getting 'Padding Errors' when decoding the posted base64-encoded string, which seems very odd to me. -
django-rest-social-auth login with give me error 400 bad request
guys im working on django-rest-social-auth that is here in github https://github.com/st4lk/django-rest-social-auth and trying to add google login to my django rest framwork app first i get code from this url https://accounts.google.com/o/oauth2/auth?response_type=code&client_id={{CLIENT_ID}}&redirect_uri={{REDIRECT_URL}}&scope=email then i send needed parameter like clientId,redirect_uri,provider and code to http://localhost:8000/api/login/social/jwt/google/ with postman and browser form but : i get HTTP 400 Bad Request error also i see this in my server console : raise AuthForbidden(args[0]) social_core.exceptions.AuthForbidden: Your credentials aren't allowed why ??? -
Adding list via queryset to ALLOWED_HOSTS
I've got objects instances within a class of UserProfile that have a field of 'website' on them. I'd like to take this list of websites from this UserProfile table in my database and append them to the ALLOWED_HOSTS list within the settings.py file in Django. I've figured out how to get the list of websites from the database: list(UserProfile.objects.all().values_list('website', flat=True) At this point, I don't know how to concatenate this list with the ALLOWED_HOSTS list within the settings.py file. Any advice would be appreciated! -
'Specifying a namespace in include() without providing an app_name'
Hi there just trying out django and I have the following urls files respectively. However, when I run the server and try to browse; I get this error. File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\urls\conf.py", line 39, in include 'Specifying a namespace in include() without providing an app_name ' django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead. project/urls.py from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^reviews/', include('reviews.urls', namespace='reviews')), url(r'^admin/', include(admin.site.urls)), ] app/urls.py from django.conf.urls import url from . import views urlpatterns = [ # ex: / url(r'^$', views.review_list, name='review_list'), # ex: /review/5/ url(r'^review/(?P<review_id>[0-9]+)/$', views.review_detail, name='review_detail'), # ex: /wine/ url(r'^wine$', views.wine_list, name='wine_list'), # ex: /wine/5/ url(r'^wine/(?P<wine_id>[0-9]+)/$', views.wine_detail, name='wine_detail'), ] What could be doing wrong? -
Python - MySQL Lock wait timeout exceeded constantly
I've set my cursor READ COMMITTED, but nothing seems to help or solve this. I constantly get this lockwait, anything else I can do? I'm inserting/updating 985,540 items into a table with 4,920,869 items and committing every 1,000 items. It breaks every time around ~380k for some odd reason. Here's my SHOW ENGINE INNODB STATUS: srv_master_thread loops: 16856 srv_active, 0 srv_shutdown, 20149 srv_idle srv_master_thread log flush and writes: 37005 OS WAIT ARRAY INFO: reservation count 499310 OS WAIT ARRAY INFO: signal count 781476 Mutex spin waits 198615, rounds 499887, OS waits 11297 RW-shared spins 537570, rounds 14378222, OS waits 432975 RW-excl spins 83386, rounds 2497252, OS waits 49663 Spin rounds per wait: 2.52 mutex, 26.75 RW-shared, 29.95 RW-excl LATEST FOREIGN KEY ERROR 2018-02-04 11:02:41 2b9f61f86700 Transaction: TRANSACTION 809840065, ACTIVE 2 sec inserting mysql tables in use 1, locked 1 2246 lock struct(s), heap size 292392, 2969 row lock(s) MySQL thread id 27969, OS thread handle 0x2b9f61f86700, query id 10539208 avails update INSERT INTO main_itemidmapping (platform_id, id_value, id_type) VALUES ('zsTbcpfJg0o', '10.5240/A949-6511-8D36-5F0E-17B8-P', 'Eidr2') Foreign key constraint fails for table `avails`.`main_itemidmapping`: , CONSTRAINT `main_itemidmapping_ibfk_1` FOREIGN KEY (`platform_id`) REFERENCES `main_iteminstance` (`platform_id`) Trying to add in child table, in index `platform_id_2` tuple: DATA TUPLE: 6 … -
QuerySet to Dictionary
Models.py has below tables class Question(models.Model): Question_Id = models.AutoField(primary_key=True) Question_Text = models.TextField(max_length=1000) def __str__(self): return self.Question_Text def __int__(self): return self.Question_Id class QuestionChoices(models.Model): Choice_Id = models.AutoField(primary_key=True) Question_Choices_Question_Id = models.ForeignKey("Question", on_delete=models.CASCADE) Choice = models.TextField(max_length=500) Is_Right_Choice = models.BooleanField(default=False) Want to retrieve all the Question_Text from Question and the Choice from QuestionChoices Table. I tried with the view as def QuestionDisplay(request): retrieved_questions_id = {Question.objects.all().values( "Question_Id", "Question_Text")} display_content = {retrieved_questions_id: retrieved_questions} return render(request, 'cgkapp/Question_page.html', context=display_content) but its returning the queryset on retrieved_question_id. How I can convert this into a dictionary so that I can render this in my html as JSON array. -
Fix order of Django migrations
I have several apps in my Django project. One of the apps (app_one) has a migration that depends on migrations from the other app (app_two) being installed. It is initial migration of app_one and it looks like this: def import_data(apps, schema_editor): schema_model = apps.get_model('app_two', 'Model') # do import def drop_data(apps, schema_editor): schema_model = apps.get_model('app_two', 'Model') # undo import class Migration(migrations.Migration): dependencies = [ ('app_two', '0005_auto_20180127_2155') ] operations = [ migrations.RunPython( import_data, reverse_code=drop_data ) ] Currently in order to install the database I need to manage.py migrate app_two and only after that do manage.py migrate, because otherwise I get an error on this migration that relation Model from app_two does not exist. Also I'm unable to run tests manage.py test normally due to the same error. It seems that Django ignores dependency in this migration for some reason. How do I fix that? -
What is the right way to create thumbnails with FK?
I am trying to create some thumbnails with FK, but I'm getting an error: AttributeError: 'PngImageFile' object has no attribute '_committed' Here is my models.py : import uuid import os from django.conf import settings from PIL import Image from django.db import models from django_extensions.db.models import TimeStampedModel class ImageModel(TimeStampedModel): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=255, null=True) image = models.ImageField(null=True, upload_to='/%Y/%m/%d/') def save(self, *args, **kwargs): instance = super().save(*args, **kwargs) self.create_thumbnails(instance) def create_thumbnails(self, instance): sizes = ((100, 100), (200, 200)) infile = self.image.name for size in sizes: outfile = os.path.splitext(infile)[0] + "_thumbnail" im = Image.open(self.image) im.thumbnail(size) im.save(settings.MEDIA_ROOT + outfile, 'PNG') Thumbnail(image=instance, thumbnail=im).save() class Thumbnail(TimeStampedModel): image = models.ForeignKey('ImageModel', on_delete=models.CASCADE, related_name='thumbnails') thumbnail = models.ImageField(null=True, upload_to='/%Y/%m/%d/') Maybe it's better to change 'ulpoad_to' to 'self.id/' and get rid of Thumbnail model?