Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
request media files in django when the debug is false
i tried to set media root and media url in but when the debug is false don't return anything settings.py ... DEBUG = False ALLOWED_HOSTS = [ '127.0.0.1', '0.0.0.0', ... ] ... STATIC_URL = 'static/' STATICFILES_DIRS = [ BASE_DIR / "static", ] STATIC_ROOT = BASE_DIR / 'staticfiles' MEDIA_ROOT = BASE_DIR / 'media' MEDIA_URL = 'media/' urls.py ... urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) ... What should i do to return media files in my projects -
Django constraint - allow only one object with same bank/mortgage and status that is not equal to DRAFT
I have a model Application with fields bank, mortgage and status. For same bank and mortgage I want to allow only one application with status different from DRAFT. class Application(..): bank = .. mortgage = .. status = .. # draft, active, in_progress etc. So there can be multiple applications like these: # ok Application(bank=1, mortgage=2, status='draft') # ok, tuple mortgage and bank already exists but but status is draft Application(bank=1, mortgage=2, status='draft') # ok, tuple mortgage and bank already exists but status is active Application(bank=1, mortgage=2, status='active') # ERROR - tuple mortgage and bank already exists and there is already one object with same tuple bank, and non-draft status Application(bank=1, mortgage=2, status='in_progress') # ok - bank is different Application(bank=3, mortgage=2, status='active') In words, I can't create an application with same bank and same mortgage and status that is not draft if there is already an application with same bank and mortgage and status that is not draft. Is it possible to do such constraint? Would CheckConstraint work? -
possible alternative to psycopg2.connect
I have made a chatting app in django (with log in and sign up) , and I have configured the database (created tables through the pgadmin4 gui) my sign-up function is something like this : @csrf_exempt def signUp(request): IP = request.META.get('REMOTE_ADDR') jned = json.loads(request.body) email = jned['email'] password = jned['password'] user_id = tokenGen() user_token = tokenGen() now = int(time.time()) create_user = f'''insert into auth_user(idx,email,passwordx,ip,utime,tokenx) values ('{user_id}','{email}','{password}','{IP}','{now}','{user_token}')''' try: connection = psycopg2.connect(user="postgres", password="0000", host="127.0.0.1", port="5432", database="project1") except: print('error in connection ') cursor = connection.cursor() cursor2 = connection.cursor() cursor2.execute(f"SELECT * FROM auth_user WHERE email = '{email}'") if cursor2.rowcount >0 : print('email already exists') return HttpResponse(json.dumps({'status':'email already exists' , 'done':False})) else: values('{jned['email']}','{ip}','{hashit(jned['password'])}','{token}',{int(time.time())})") cursor.execute(create_user) connection.commit() return HttpResponse(json.dumps({'status':'never used this website huh?' , 'done':True, 'token':user_token})) everything works perfectly fine. but I think that I am connecting to the database in a wrong way, all the tutorials on youtube setup the database in settings.py , taking a completely different path (they use models and django.db). so , the question is : can I push this to production or should I write all the database models even though I don't need them? -
How send value from view to template form url
i am passing parameter in url i want to pass parameter from veiw by render() function and put in form url template. url.py path('log/<x>', csrf_exempt(views.login) , name='login-bot') veiw.py def login(request, x=123): return render(request, 'chat/user_info_add.html', {'x':x} ) template (user_info_add.html) here look i have put value in x={{x}} but not working mean not geting value------- in action attribute of form i tried '{{x}}' and work just as string not that value which i was sending from veiw but without quote it giving template syntax error <div class="first_loginbox"> <form action="{% url 'chat:login-bot' x={{x}} %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class ="second_loginbox"> <label for="login_screen" class="label_login">Add Info</label><br> <input type="email" class="form-control marg" " name="email" placeholder="Enter Email Address"> <input id="css2" type="text" class="form-control marg " name="name" placeholder="Enter your Name"> <button id = "css3" class="btn btn-outline-success">Login</button> </div> </form> </div> please if any one could help how we put value inside {% url 'chat:login-bot' {{x}} %} error Exception Type: TemplateSyntaxError Exception Value: Could not parse the remainder: '{{x}}' from '{{x}}' -
Subscribe to all changes of instances of the model
I'm using this example: https://djangochannelsrestframework.readthedocs.io/en/latest/examples/model_observer.html I'm displaying all the data from model Post on the page in the table. I decided to use websockets for this and stuck on this issue: If I'm changing/adding/deleting instances of model using django admin panel - all works fine, but if I'm doing changes by hand in the shell or my celery worker updating the database - then nothing happens, what can be an issue? My code so far: consumers.py from djangochannelsrestframework import permissions from djangochannelsrestframework.generics import GenericAsyncAPIConsumer from djangochannelsrestframework.mixins import ListModelMixin from djangochannelsrestframework.observer import model_observer from .models import Post from .serializers import PostSerializer class PostConsumer(ListModelMixin, GenericAsyncAPIConsumer): queryset = Post.objects.all() serializer_class = PostSerializer permissions = (permissions.AllowAny,) async def connect(self, **kwargs): await self.model_change.subscribe() await super().connect() @model_observer(Post) async def model_change(self, message, observer=None, **kwargs): await self.send_json(message) @model_change.serializer def model_serialize(self, instance, action, **kwargs): return dict(data=PostSerializer(instance=instance).data, action=action.value) my template: index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <!-- CSS only --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous" /> <title>Code with SJ</title> </head> <body> <div id="app" class="row mt-5"> <div class="col-1"></div> <div class="col-10"> <div class="card"> <p class="card-header">Display list of all the posts in Real-Time</p> <div class="card-body"> <table class="table align-middle mb-0 bg-white"> <thead … -
Is there a way for graphene to accept plain text?
When I send a query with Content-Type as plain text, I keep getting a {"errors":[{"message":"Must provide query string."}]} When I convert the query to a JSON object and change the content-type to json, which is painful to do tbh, it works fine. This looks like a django-graphene issue. Is there a setting I need to set to allow for plain text? -
Pyinstaller and django Failed to colelct submodules
Here is my command: pyinstaller --noconfirm --onedir --console --log-level "ERROR" --hidden-import "rest_framework.schemas" --hidden-import "django.contrib.gis.utils" --paths "C:/Users/a/Documents/GitHub/compute-local/backend/.env/Lib/site-packages" --additional-hooks-dir "C:/Users/a/Documents/GitHub/compute-local/backend/extra-hook" --hidden-import "djoser.urls" --paths "C:/Users/a/Documents/GitHub/compute-local/backend/.env/Lib/site-packages/djoser/urls" --paths "C:/Users/a/Documents/GitHub/compute-local/backend/.env/Lib/site-packages/rest_framework/schemas" --hidden-import "djoser" --hidden-import "rest_framework" "C:/Users/a/Documents/GitHub/compute-local/backend/manage.py" And here are the errors WARNING: Failed to collect submodules for 'djoser.urls' because importing 'djoser.urls' raised: django.core.exceptions.ImproperlyConfigured: Requested setting REST_FRAMEWORK, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. 763 WARNING: Failed to collect submodules for 'rest_framework.schemas' because importing 'rest_framework.schemas' raised: django.core.exceptions.ImproperlyConfigured: Requested setting REST_FRAMEWORK, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Can someone help me navigate this issue? -
Django Standalone Script in Django 4.1
I am trying to run a standalone script in django 4.1. I have the setup as suggested in this post at the top of my file: Django Standalone Script import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "path_to_settings.settings") import django django.setup() However, on the 4th line, I get the following error: ModuleNotFoundError: No module named 'sport_api' How do I get around this error? -
How to style Django forms according to html theme
Here is the scenario iam trying style default django select form field as my html select field. But the output is different how can fix this. This is how i need my output This is what iam getting Html code <select class="selectpicker" data-live-search="true" data-width="100%"> <option>Select</option> <option data-tokens="Convertible">Convertible</option> <option data-tokens="Coupe">Coupe</option> <option data-tokens="Hatchback">Hatchback</option> <option data-tokens="Sedan">Sedan</option> <option data-tokens="SUV">SUV</option> </select> My Django form code fromPlace = forms.ModelChoiceField(queryset=Place.objects.order_by('name'),widget=forms. Select(attrs={'class': 'selectpicker'})) -
Django select_related()
i have a problem with my Queryset. class Category(models.Model): name = models.CharField(max_length=50, unique=True) class Outlay(models.Model): category = models.ForeignKey( Category, models.PROTECT, related_name='outlay_set', null=True, blank=True) name = models.CharField(max_length=50) price= models.DecimalField(max_digits=8, decimal_places=2) date = models.DateField(default=datetime.date.today, db_index=True) I tried to get from Category model price for the every category using relations with ForeignKey. I've created this : queryset = Outlay.objects.all().prefetch_related('category') and get: <QuerySet [<Outlay: 2022-10-03 Forage 175.00>, <Outlay: 2022-10-03 Wodka 232.00>]> Mayby someon will help me how i can pull out only prices?? -
How you manage the output values is a string in django
In my Django backend db, results are stored in result column, and result itself looks like this: result = [ {"pod_name": "kafka-9", "resolution_ms": 60000,"value": 420.85}, {"pod_name": "kafka-3", "resolution_ms": 60000, "value": 418.0}, ... ] When I do the get_results from the filter results = DjangoCeleryResultsTaskresult.objects.filter(task_id=taskname).values('result') just_res = list(results)[0].values() just_res is a dictionary values, dict_values(['[{"pod_name": "kafka-9", "resolution_ms": 60000, "value": 420.85}, {"pod_name": "kafka-3", "resolution_ms": 60000, "value": 418.0}]']) However, I want my just_res is a list of nested dictionary, like it is stored in db. I tried: service_results = list(just_res)[0] but this only convert me a string, and convert that string to a list is another nightmare, cannot just use list() method. Can you help me figure out either? convert the values of string(just_res) into a list? or A way to pull django results as a list from db? In all, not sure why django filter objects values(), I can only get results as a string, not the original datatype. Am I using it wrong or another other approach? Thanks! -
Change URL for wagtail blog index page
I currently have a website where the home page at www.mysite.com is the wagtail blog index page I wish to move the blogindex page to another url I can easily have a different homepage by amending my urls.py file: #original path("", include(wagtail_urls)) #new path( "", TemplateView.as_view(template_name="pages/newhomepage.html"), name="newhomepage", ), However I would like the blogindex page available at e.g. myste.com/blog but I am not sure how to go about this. Adding the following to urls.py does not do it path("blog/", include(wagtail_urls)) -
Python & Django: Cannot Retrieve Defaults From 2 Layer Deep Foreign Key Relationship
I found this trick, which might be a hack, to set default values when the field is a foreign key to another database: class House(models.Model): name = models.CharField(max_length=100, unique=True) address = models.CharField(max_length=300, null=True, blank=True) def __str__(self): return name @classmethod def get_default(cls): return cls.objects.filter(address="5360 Wallaby Lane").first().pk class Meta: ordering = ["name"] When constructing another class that references this field, we can set a default as follows: class Neighborhood(models.Model): favourite_house = models.ForeignKey("civilization.House", on_delete=models.PROTECT, default=House.get_default()) name = models.CharField(max_length=100, unique=True) @classmethod def get_default(cls): return cls.objects.filter(name="Upper Snootington").first().pk This works fine. As long as this function referencing a second layer isn't called by another default field for a table, Django doesn't complain. Once I tie this in as a default to another model, however: class City(models.Model): favourite_neighborhood = models.ForeignKey("civilization.Neighborhood", on_delete=models.PROTECT, default=Neighborhood.get_default()) Django throws exceptions "django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.". It seems this is pretty specific to that second layer of default retrieval. The best I can surmise is that Django is trying to interact with the models while it builds the models with that second layer referencing another model. Something tells me this is a hack and there's a better way... -
Custom permission not working Django/REST
from rest_framework import permissions class UserButEmailVerified(permissions.BasePermission): def has_permission(self, request, view): if request.user.is_authenticated: return True def has_object_permission(self, request, view): if request.user.email_is_verified: return True return False == Persmission class from .permissions import UserButEmailVerified @api_view(["POST"]) @permission_classes([UserButEmailVerified]) def sendMessage(request): print(request.user.email_is_verified,"emai") == also gets called even if email_is_verified returns False=? I got the feeling that UserButEmailVerified isnt called at all, print statements are not getting executed, if I try to login unauthorized at all, I do not get access.... I know i could achive this without the permission class, but I want to learn it, so what am I doing wrong? -
Error when running custom manage.py command
I'm building a multitenant app based on this page https://www.section.io/engineering-education/implement-multitenancy-with-multiple-databases-in-django/#use-middlewares-for-tenant-specific-database-routing. It asks to create a custom manage.py (named myapp_manage.py) to create a superuser, so that way i can point the database that i want to run the command like this: python myapp_manage.py databasename createsuperuser --database=databasename Everything was ok, i could run the command without problems, but now, when i try to run it, it gives me an error: django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I don't understand why this error is showing because the environment in custom manage.py is configured exactly like the standard manage.py. Custom manage.py: #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys from myapp.middleware import set_db_for_router if __name__ == "__main__": """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'al_project.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc # new from django.db import connection args = sys.argv db = args[1] with connection.cursor() as cursor: set_db_for_router(db) del args[1] execute_from_command_line(args) Standard manage.py: … -
Server-Side Data table Error Due to URL Length
I'm currently working on a django project that uses server-side data tables. When I try to generate a table with less than 18 columns, it would work. However, when I choose to have more than 18 columns in my table, I get the error 404 - File or directory not found. I think this may be due to the length of the URL. Just to give an idea, the URL generated for 31 columns contains over 1K characters. I would appreciate some insight on what I could change to resolve this problem. Below is a part of my code for the data table: var table = $('#example').DataTable( { "initComplete": function(settings, json) { table.buttons().container().appendTo( $('div.column.is-half', table.table().container()).eq(0)); }, scrollX: true, scrollY: "500px", lengthChange: false, pageLength:5000, buttons: [ 'excel'], serverSide: true, sAjaxSource: "(insert address here)" }) -
How to pass variables between class based Views in Django?
I've created url-shorter service using Django. For creating short link i use CreateView: class LinkCreate(CreateView): form_class = CreateLink template_name = "index.html" success_url = reverse_lazy('users_links') def form_valid(self, form): if self.request.user.is_authenticated: form.instance.creator = self.request.user self.link_short = generate_short_link() self.request.session["new_link"] = self.link_short form.instance.link_short = self.link_short return super().form_valid(form) # Showing last 5 shorted links on the page def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['object_list'] = URL.objects.all().order_by('-id')[:5] return context After creating new link user is redirected to page "users_links" where he should see new shotred link. For this reason in template i use something like that: {% if request.session.new_link %} <div> Your new link: request.session.new_link </div> {% endif %} The problem is user see that 'div' all the time till the end of session. I think this is wrong decision to using session variables in this case, but i don't know how to pass variable between views in another way. I'm newbie in Django, can you please give me advice how to do it in the right way? -
Django queryset does not return for repeated value
payments_modes=Payment.objects.filter(content_type=content_type,content_id__in=content_id).values_list('payment_mode',flat=True) order_ids = payments_modes.filter().values_list('content_id',flat=True) ledger_name = Order.objects.filter(id__in=order_ids,seller=user.company,status__in = [ORDER_STATUSES.DELIVERED,ORDER_STATUSES.COMPLETED]).values_list('buyer__name',flat=True) -
Django does not log in custom superuser with correct password and username [closed]
I know this is a recurrent question but my case is pretty weird. I am working with a partner and on his laptop (with Linux) everything is going well. However, I tried to run the same code two times: one on Windows and the other one on Archlinux and in both of them I am not able to log in with the correct username and password. The superuser was created with 'python manage.py createsuperuser' the there weren't errors in the console. Superuser with its password (hashed) is correctly written in PostgreSQL database, so I suspect that the problem is in the reading or with the desencryptation. I copy below the relevant parts of models.py and admin.py. #models.py class AccountManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): values = [email] field_value_map = dict(zip(self.model.REQUIRED_FIELDS, values)) for field_name, value in field_value_map.items(): if not value: raise ValueError('The {} value must be set'.format(field_name)) email = self.normalize_email(email) user = self.model( email=email, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise … -
Modelling complex django model relations efficiently
I am programming a django website for oragnizing events where I need to be able to store information about which attendees will stay for meals. I have currently got it working in a way which I think is really not optimal, and I would like to improve it. I would be glad to hear any ideas about how you would go about it. What I need So, for each event (which can have a duration of a variable number of days) I need to be able to display what I call a meals table. This table will hold information about each day's meals. Each day has three meals (breakfast, lunch and dinner). Each meal needs to contain information about the number of people that are staying for that meal plus the dish that each of those people are going to have from the menu. The menu also contains a variable number of dishes that can be modified by the administrator of that event (the menu is the same for every meal). So, the general concept diagram would be something like this: Event |_ Meal Table |_ Day 1 |_ Breakfast \_ Dish 1 -> Nº of people \_ Dish 2 … -
Auth Management with Django Rest Framework, Next.JS and?
I want to get my head down into a small community website using Django Rest Framework as a backend and Next.JS as a frontend. I am struggling with the authentication module. What is best practice? I thought about using Firebase as an auth provider but the implementation is quite hard - or at least I could not find good documentation. I am now thinking of using the Djoser library to have django handle all authentication and user management. My question is: What would you recommend to use? The official DRF website has a ton of third-party packages on this topic but I just can decide which one to use (https://www.django-rest-framework.org/api-guide/authentication/#third-party-packages) Thank you -
Type object 'Book' has no attribute 'objects'
I am getting error AttributeError: type object 'Book' has no attribute 'objects' while running my django project. Models.py from django.db import models # Create your models here. """Create or Save Model Instance. """ class BookManager(models.Manager): def create_book(self, title): book = self.create(title=title) return book """Book Model""" class Book(models.Model): title = models.CharField(max_length=100, verbose_name="Book_Title") """Str Display. """ def __str__(self): return self.title """To Save Model Instance. """ object = BookManager() views.py from django.views import View from .models import Book from django.http import HttpResponse # Create your views here. """Default View """ class default_view(View): def get(self, request): queryset=Book.objects.all() return HttpResponse(queryset) def post(self, request): # Getting Value of title title = request.POST.get('title') """Creating Book Instance. """ book = Book(title=title) book.save() return HttpResponse('saved') Error Internal Server Error: /model_instance Traceback (most recent call last): File "D:\Concept_and_Project\Web Development\BackEnd\Django Framework\Model\lib\site- packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "D:\Concept_and_Project\Web Development\BackEnd\Django Framework\Model\lib\site- packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Concept_and_Project\Web Development\BackEnd\Django Framework\Model\lib\site- packages\django\views\generic\base.py", line 103, in view return self.dispatch(request, *args, **kwargs) File "D:\Concept_and_Project\Web Development\BackEnd\Django Framework\Model\lib\site- packages\django\views\generic\base.py", line 142, in dispatch return handler(request, *args, **kwargs) File "D:\Concept_and_Project\Web Development\BackEnd\Django Framework\Model\category\Model_Instance\Instance_method\views.py", line 9, in get queryset=Book.objects.all() AttributeError: type object 'Book' has no attribute 'objects' [04/Oct/2022 19:36:17] "GET /model_instance HTTP/1.1" … -
Is there a way to dynamically annotate value from JSONField using another annotation in Django?
What I have is a following annotation: member_qs = RoomMember.objects.filter(room_id=OuterRef('id'), ...) qs = Room.objects.annotate( person_role=Case( When(Exists(member_qs), then=Subquery(member_qs.values_list('role', flat=True))), default=Value(request.user.global_role) ), person_permissions=Case( When(Q(person_role='creator'), then=F('role_permissions__creator')), When(Q(person_role='moderator'), then=F('role_permissions__moderator')), When(Q(person_role='member'), then=F('role_permissions__member')), When(Q(person_role='authenticated'), then=F('role_permissions__authenticated')), default=F('role_permissions__anonymous') ), can_chat=F('person_permissions__chat_send'), can_add_videos=F('person_permissions__queue_extend'), ) ... where role_permissions is a JSONField in this form: {"role_name": {"permission_name": true|false}} This works but results in an ugly and very slow SQL. What I want is to simplify annotation of person_permissions or get rid of it completely, but I can't use person_role directly because F is hard-coded. -
IntelliJ python debugger `ModuleNotFoundError: No module named 'logging.handlers'; 'logging' is not a package`
While using IntelliJ with python I cannot make the debugger work while testing because it always appear: ModuleNotFoundError: No module named 'logging.handlers'; 'logging' is not a package Checking the Traceback I encountered the problem shown in the image below but I do not know if it really points in some direction to solve the issue: I tried installing logging separately without any effect. On the other hand logging works perfectly in the python console. -
Infinate migration for an intact model
util class UploadTo: def __init__(self, folder, filename_suffix=""): self.folder = folder self.filename_suffix = filename_suffix def _get_filename(self, instance, filename): _, file_extension = os.path.splitext(filename) result = str(instance.a_uuid) if self.filename_suffix: result += "-{}".format(self.filename_suffix) result += file_extension return result def save_path(self, instance, filename): tmp_filename = self._get_filename(instance, filename) result = "{}/{}".format(self.folder.value, tmp_filename) return result model class Sound(UuidMixin, PhraseMixin, CommentMixin): british_sound = models.FileField(blank=True, null=False, default="", upload_to=UploadTo(folder=UPLOAD_TO.VOCABULARY_SOUND_FOLDER, filename_suffix="british").save_path) american_sound = models.FileField(blank=True, null=False, default="", upload_to=UploadTo(folder=UPLOAD_TO.VOCABULARY_SOUND_FOLDER, filename_suffix="american").save_path) Message Migrations for 'vocabulary_sounds': vocabulary_sounds/migrations/0009_alter_sound_american_sound_alter_sound_british_sound.py - Alter field american_sound on sound - Alter field british_sound on sound Migration class Migration(migrations.Migration): dependencies = [ ('vocabulary_sounds', '0008_alter_sound_american_sound_alter_sound_british_sound'), ] operations = [ migrations.AlterField( model_name='sound', name='american_sound', field=models.FileField(blank=True, default='', upload_to=general.model_aux.UploadTo.save_path), ), migrations.AlterField( model_name='sound', name='british_sound', field=models.FileField(blank=True, default='', upload_to=general.model_aux.UploadTo.save_path), ), ] Copy Snippet Edit Snippet Wordwrap class Sound(UuidMixin, PhraseMixin, CommentMixin): british_sound = models.FileField(blank=True, null=False, default="", upload_to=UploadTo(folder=UPLOAD_TO.VOCABULARY_SOUND_FOLDER, filename_suffix="british").save_path) american_sound = models.FileField(blank=True, null=False, default="", upload_to=UploadTo(folder=UPLOAD_TO.VOCABULARY_SOUND_FOLDER, filename_suffix="american").save_path) Migrations for 'vocabulary_sounds': vocabulary_sounds/migrations/0009_alter_sound_american_sound_alter_sound_british_sound.py - Alter field american_sound on sound - Alter field british_sound on sound class Migration(migrations.Migration): dependencies = [ ('vocabulary_sounds', '0008_alter_sound_american_sound_alter_sound_british_sound'), ] operations = [ migrations.AlterField( model_name='sound', name='american_sound', field=models.FileField(blank=True, default='', upload_to=general.model_aux.UploadTo.save_path), ), migrations.AlterField( model_name='sound', name='british_sound', field=models.FileField(blank=True, default='', upload_to=general.model_aux.UploadTo.save_path), ), ] Whenever I carry out makemigrations, …