Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DJANGO Problem at rendering Form - Dropdownlist not show
When I rendering {{form.as_p}}: all input text is fine display as expected (from model.CharField) all select option just showing label without dropdownlist (from model.ForeignKey) but when i use w3shool html editor, copying code from view page source html and paste in w3.html editor all is fine, select option is appear on that. So, What is wrong? please help me get the answer, and fix the problem thank you models.py class Project(models.Model): project_no = models.CharField(max_length=10, blank=True) project_name = models.CharField(max_length=100, blank=True) project_no_file = models.CharField(max_length=10, blank=True) project_div = models.ForeignKey(Division, on_delete=models.CASCADE) project_cord = models.ForeignKey(Inspector, on_delete=models.CASCADE) def __str__(self): return self.project_no class Inspector(models.Model): inspector_name = models.CharField(max_length=50, blank=True) inspector_biro = models.ForeignKey(Biro, on_delete=models.CASCADE) def __str__(self): return self.inspector_name class Division(models.Model): div_name = models.CharField(max_length=50, blank=True) def __str__(self): return self.div_name views.py class AddView(CreateView): template_name = "launching/adddata.html" model = Project fields = '__all__' urls.py re_path(r'^project/add/$', AddView.as_view(), name='create') adddata.html <div class="container"> <form method="post" enctype="multipart/form-data" name="form_add"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Save"> </form> </div> result in browser dropdownlist for Project div and project cord not show result in W3.editor all is fine when its run the rendering code in w3editor -
Is this code correct to send email (django)?
Test.py email = EmailMessage() email['from'] = 'Your Name' email['to'] = 'name@gmail.com' email['subject'] = 'Welcome to Ourr Website!' email.set_content("Hope You are doingg great.") with smtplib.SMTP(host='smtp.gmail.com', port=587) as smtp: smtp.ehlo() smtp.starttls() smtp.login('example@gmail.com', 'password: ********') smtp.send_message(email) print("Done") When I exicute I'm getting timeout error(10060), can any one help Thank out -
Styling PhoneNumberPrefixWidget in django with crispyforms
I'm rendering a crispy form and I've added a PhoneNumberPrefixWidget from this library, after adding it to crispy form's layout I can't change the style. Is there any way to achieve this? The library owns almost any documentation. My model: class Contact(BaseModel): person_phone_number = PhoneNumberField( verbose_name="Número de teléfono", null=True, blank=True ) Form: class ContactForm(BaseForm): person_phone_number = PhoneNumberField( widget=PhoneNumberPrefixWidget(initial="IN"), label=('Número de Teléfono'), ) class Meta: model = Contact exclude = [] Layout: self.layout.fields.append( self.make_row( [ "person_phone_number", ], size=6, ) ) -
How to setup "Hybrid Architecture" in Django while using Svelte.js?
I was trying to setup a svelte js in django to build an ecommerce website. Then, I found out there are 3 architecture : Server-First Architecture :bits of js scattered throughout django templates and static files. Client-First Architecture: Front end is a single page app that treats Django as an REST API Hybrid Architecture: It is a combination of both (client and server)-First Architecture. I choose Hybrid Architecture because I don`t want to wrestling with CORS or any 3rd party framework and having disadvantage of not taking advantage of using js tooling. Now the questions are: How do I setup Hybrid Architecture so that I can use Django Features alongside with Svelte js Features ? Can I setup Single Page App using Hybrid Architecture in Django? Is Single Page App good for Ecommerce in Django Note: I don`t want to use any Django libs such as Django-Svelte etc to setup it . I just want to install and setup with npm and webpack inside django just like normal setups. -
Django email logging isn't sending emails
I've implemented logging within my settings file, but no emails are being sent when a 500 error is hit. I'm on django 3.x All of the email settings within my settings file work. These settings are successfully used to deliver account confirmation emails, for example. EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'support@########' EMAIL_HOST_PASSWORD = '#######' DEFAULT_FROM_EMAIL = 'support@######' SERVER_EMAIL = 'support@########' EMAIL_PORT = ##### EMAIL_USE_TLS = True LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler' }, }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': False, }, } } Thanks! -
django.db.utils.OperationalError: (1071, 'Specified key was too long; max key length is 3072 bytes')
I am getting this error when migrating: django.db.utils.OperationalError: (1071, 'Specified key was too long; max key length is 3072 bytes') My configuration: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'myname', 'USER': '', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '3306', 'CHARSET': 'utf8', } } This happened after adding indexes to my model: class MsTune(models.Model): class Meta: indexes = [ models.Index(fields=['name', 'title', 'alt_title', 'index_standard_1', 'index_standard_2', 'index_gore_1', 'index_gore_2', 'alt_index_gore_1', 'alt_index_gore_2', 'alt_index', 'alt_index_standard_1', 'alt_index_standard_2', 'bass', 'variations' ]), ] What can the reason be? My database uses UTF-8 and, as far as I know, Django's MySQL connector uses InnoDB by default. Django 3.1, MySQL 8.0.23, Python 3.7.3 -
custom static files not loading in django project
I have a django project where I have kept all the static files in a project level static directory. I have included STATIC_URL = "/static/" STATIC_ROOT = os.path.join(BASE_DIR, 'static') in the settings.py. ALso I have added + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) to the urlpatterns in the project level urls.py. My issue is that some of the static files load whereas some do not. For. eg. I am using django_google_maps and the (example url) http://127.0.0.1:8000/static/django_google_maps/js/google-maps-admin.js loads right and the corresponding work is done. But when I try to load my custom js/css/any-static files, (example url http://127.0.0.1:8000/static/images/favicons/favicon.ico or ttp://127.0.0.1:8000/static/js/image-upload-script.js), they do not load and raise a django.views.static.serve error with 404 not found. They are right there in the directory though. I see that the static files used by third party packages are loading right but not my custom ones. What is it that I am missing? Do we require something else to load our custom js/css files?? And yes I have used {% load static %} in my template. -
Django | argon2-cffi not hashing from admin panel
I am using argon2-cffi to hash users' passwords, however when logging into the admin panel and creating a new user, the password is not being hashed, it stays as the raw password. How can i overwrite this configuration? Or, what could I implement to hash the accounts that have raw passwords? I tried what the answer of this question suggested but hasn't worked. I haven't been able to find any resourceful information about it. -
Obtaining full requested url address
I'm looking to obtain the full requested url within python/django. I'm wondering what package might help me do this. For example, if someone goes to example.com/my-homepage, I want to capture the string 'example.com/my-homepage' in python. Thanks! -
Updating a list within a class
Is it possible to update a list within a class based on instance details? I would like to do something like this: from formtools.wizard.views import SessionWizardView class ContactWizard(SessionWizardView): form_list = [ # a list of forms used per step (S1, Q1), (S2, Q2), (S3, Q3), ] def form_updater(self): if self.get_cleaned_data_for_step("0") != None: form_list.append((S3, Q3),) return form_list However, I get thrown an error when I try to make the following call: ContactWizard.form_updater(ContactWizard) ## error: get_cleaned_data_for_step() missing 1 required positional argument: 'step' Any help or guidance that you can provide would be VERY greatly appreciated. -
URL pathfinder in Django - any workaround when it keeps redirecting me to main view?
Sorry for being an embarrassing noob, but I have managed to complete like 99% of the Django Girls tutorial only to realize that there is one essential function in my basic blog site that's not working - the post titles on the main view don't link to their respective post views, even though the code seems alright to me... Guess I am really missing a glaringly obvious mistake! I was considering to switch from pk to slug, could that be an effective workaround? views.py from django.shortcuts import render, get_object_or_404 from django.shortcuts import redirect from django.utils import timezone from .models import Post from .forms import PostForm def post_list(request): posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date') return render(request, 'blog/post_list.html', {'posts': posts}) def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) return render(request, 'blog/post_detail.html', {'post': post}) def post_new(request): if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.published_date = timezone.now() post.save() return redirect('post_detail', pk=post.pk) else: form = PostForm() return render(request, 'blog/post_edit.html', {'form': form}) def post_edit(request, pk): post = get_object_or_404(Post, pk=pk) if request.method == "POST": form = PostForm(request.POST, instance=post) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.published_date = timezone.now() post.save() return redirect('post_detail', pk=post.pk) else: form = PostForm(instance=post) return render(request, 'blog/post_edit.html', {'form': form}) urls.py … -
{% for post in posts %}} in home.html not rendering anything Django
Im following Corey Schafers tutorial: https://www.youtube.com/watch?v=qDwdMDQ8oX4&list=PL-osiE80TeTtoQCKZ03TU5fNfx2UY6U4p&index=3&ab_channel=CoreySchafer This is my home.html file: <!DOCTYPE html> <html> <head> <title></title> </head> <body> {% for post in posts %} <h1>{{ post.title }}</h1> <p>By {{ post.author }} on {{ post.date_posted }}</p> <p>{{ post.content }}</p> {% endfor %} asdf </body> </html> I know its the one being used because "asdf" is being rendered: But the title, content, and nothing really renders here. I have been following this tutorial doing everything the way he does. This is my views.py file: from django.shortcuts import render posts = [ { "author": "JohnsMS", "title": "Blog Post 1", "content": "First post content", "date_posted": "August 27, 2017" }, { "author": "John Doe ", "title": "Blog Post 2", "content": "Second post content", "date_posted": "June 27, 2018" } ] def home(request): context = { "post": posts } return render(request, "blog/home.html", context) def about(request): return render(request, "blog/about.html") I even added a print statement in the home function, and the context was correct. This is how it should render (from the tutorial): This is my directory structure: . ├── blog │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-39.pyc │ │ ├── admin.cpython-39.pyc │ │ ├── apps.cpython-39.pyc │ │ … -
Django rest framework documentation JSONParser().parse(request) doesn't work
I followed official documentation tutorial and in POST method JSONParser().parse(request) didn't work so i just replaced it with request.POST then it worked. Is anything wrong with it? Why should i use JSONParser().parse(request) instead of request.POST? @csrf_exempt def snippet_list(request): """ List all code snippets, or create a new snippet. """ if request.method == 'GET': snippets = Snippet.objects.all() serializer = SnippetSerializer(snippets, many=True) return JsonResponse(serializer.data, safe=False) elif request.method == 'POST': data = JSONParser().parse(request) #<------------ This line serializer = SnippetSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) @csrf_exempt def snippet_list(request): """ List all code snippets, or create a new snippet. """ if request.method == 'GET': snippets = Snippet.objects.all() serializer = SnippetSerializer(snippets, many=True) return JsonResponse(serializer.data, safe=False) elif request.method == 'POST': data = request.POST #<---------- To this line serializer = SnippetSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) -
Django REST Filter Nested Objects
I have a Student model which has a Many-To-Many relationship with an Assignments model. The Assignments model has a foreign key relationship with a Scores model. This Scores model also relates to the Student to identify who the score belongs to. How would I filter my GET request so that it only returns the score for that specific user? MODELS class Rubric(models.Model): possibleScore = models.IntegerField(default=0) description = models.CharField(max_length=200,default="Correct") assignment = models.ForeignKey(Question,related_name='rubric',on_delete=models.CASCADE,blank=True,null=True) class StudentScore(models.Model): student = models.ForeignKey(to="accounts.Student",related_name="studentScore",on_delete=models.CASCADE,blank=True,null=True) rubric = models.ForeignKey(Rubric,related_name="studentScores",on_delete=models.CASCADE,blank=True,null=True) studentScore = models.IntegerField(default=0) class Assignment(models.Model): name = models.CharField(max_length=100) maxNumberOfPoints = models.IntegerField(default=100) studentsPoints = models.IntegerField(default=0) course = models.ForeignKey(Course,related_name='gradeable',on_delete=models.CASCADE) class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) studentID = models.CharField(max_length=100,unique=True) Courses = models.ManyToManyField(Course) Assignment = models.ManyToManyField(Gradeable) Views class StudentView(APIView): permission_classes = [permissions.IsAuthenticated, ] def get_object(self, request): try: # Get requesters token and identify matching student object requestToken = request.META['HTTP_AUTHORIZATION'].split(' ')[1] userObj = Token.objects.get(key=requestToken).user studentObj = Student.objects.filter(user=userObj)[0] # If requester token does not match user return permission denied if(self.request.user != userObj): raise PermissionDenied() return studentObj except Student.DoesNotExist: raise Http404 def get(self, request, format=None): student = self.get_object(request) serializer = StudentSerializer(student) return Response(serializer.data) Serializers class StudentScoreSerializer(serializers.ModelSerializer): class Meta: model = StudentScore fields = ('studentScore',) class RubricSerializer(serializers.ModelSerializer): studentScores = StudentScoreSerializer(many=True,required=False) class Meta: model= Rubric fields=('possibleScore','description','studentScores',) class AssignmentSerializer(serializers.ModelSerializer): class Meta: … -
Python Django Projects scaffolding boilerplate automation
I have django-cms project and i will use it as boilerplate, like when i got a project, i just run a command, it should generate initial setup/copy existing project with different name and changing some contenxt. For example, i have wsgi.py file """ WSGI config for mysite project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings.dev") application = get_wsgi_application() So currently the project name is mysite but when i re-genrate the same project for another client/project, the project name should be different, like it will mywebsitepro I mean, some text/code should be replaced into my given one. Anyone has idea of how i can get it done? like when we run django command django-admin startproject <projectname> You may notice, everywhere of the first generated files name is same as what we given in command argument. What is the possible solution of this? is there any tools like this? -
Django integration with a python script
I have a python script that open and mantein a websocket (socket.io) with a remote server and a django instance. For my purpose I want the script to start and stop with the django server. I would also like to exchange data between the two. In praticular django needs to be notified whenever the remote server goes offline and keep this information globally. The tricky points for me are: Start and stop django and the script at the same time. Store globally the state of the script in the django application Is there a good way to implement this? -
How should I structure my database entities with invites and recipients for e-signing web app in Django?
I am interested in implementing the following requirements for my e-signature web application. A user can create a new signing contract. That contract can include multiple users to sign. The contract creator needs to provide emails of the recipients. Every recipient will have additional data assigned, like signing details, instructions and etc. However, the invited user can still be not present in the system. This is the trickest part. Right now my following implementation is the following: I create a contract, then check if a user is present in the system by making a filter by email. If the user exists, I create a many-to-many entity ContractRecipientEvent using through intermediate table with additional data, which is assigned to the contract. I create it many-to-many because the same user can be assigned to multiple contracts. If the user is not present I create the Invitation model, set all recipient's specific data, and send an email. Then the user is registered, I run the query of all Invitations records with that email and create ContractRecipientEvent, by copying data from the Invitation model. What I don't like with my approach are the following things: Many-to-many field. I would like to just use plain … -
Django Python Error: 'dict' object has no attribute 'status_code'
Dear people i have a problem i can't solve. I get the following error after a post: 'dict' object has no attribute 'status_code' I'm using django 3.1.7 and python 3.8. Can anyone help me with this problem? I'm new to this stuff and can't seem to solve it alone. Part of the program: *body = ET.tostring(envelope, pretty_print=True) response = requests.post(url,data=body,headers=headers, auth=(gebruiker, wachtwoord)) root = ET.fromstring(response.text.encode('ascii','ignore')) if response.status_code == 200: status = 0 else: status = 1 Verwerking.objects.create(omgeving=omgnaam, Status=status, bericht=body, antwoord=ET.tostring(root, pretty_print=True).decode()) return HttpResponse()* Reponse: Internal Server Error: /woningbeheer/syncPCAind/532698 Traceback (most recent call last): File "C:\Python38\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Python38\lib\site-packages\django\utils\deprecation.py", line 116, in call response = self.process_response(request, response) File "C:\Python38\lib\site-packages\django\middleware\common.py", line 106, in process_response if response.status_code == 404: AttributeError: 'dict' object has no attribute 'status_code' [20/Mar/2021 21:35:30] "GET /woningbeheer/syncPCAind/532698 HTTP/1.1" 500 65748 Thanks in advance and if there is more information needed let me know. -
Saving Queryset data to a model from a slider
I am trying to make a tinder like app where a hiring manager can search for specific IT candidates and then like or dislike them based on their qualifications. This app is acting as a frontend for an IT staffing company and uses their ZOHO database without showing any sensitive information for the candidates. Basically, the app calls the ZOHO API, fills the candidate model with data and I have a search form that uses a Queryset to display that data. I was able to put that data into a bootstrap carousel and scroll through each candidate but now I want to make a like button that will save a candidate to whatever user is currently logged in. I made a model for this called "UserChoice" but now I am unsure how to get the Queryset data into the new model and how to tie the button to each candidate the user wants to save. Currently, the buttons on the carousel just slide to the next candidate. Any help would be appreciated I am still pretty new to Django development. views.py(match app) number_of_candidates = len(database["response"]["result"]["Candidates"]["row"]) for P in range(0, number_of_candidates): #Clean slate for a new candidate. candidate_Pkey = "" candidate_Fname … -
how to use onkeyup javascript to django inlineformset fields
there i'm trying to add onKeyup() event to my django inlineformset fields , but i dont know how to achieve it this is my models.py class Main(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) company = models.ForeignKey(Companies,on_delete=models.CASCADE) items = models.ManyToManyField(Item,through='Child') invoice_number = models.IntegerField() class Child(models.Model): main = models.ForeignKey(Main,on_delete=models.CASCADE) item = models.ForeignKey(Item,on_delete=models.CASCADE) quantity = models.IntegerField() price = models.IntegerField() function counting(result) { document.getElementById("total").value= result; } counting(0); function totalSumField () { let inp = document.querySelectorAll("#allInp > .inp"); let result=0; for(let i=0;i<inp.length;i++){ let nrx=inp[i].getElementsByClassName("price")[0].value; let dana=inp[i].getElementsByClassName("quantity")[0].value; inp[i].getElementsByClassName("totalSumField")[0].value=(price*quantity); } function totalSum () { let inp = document.querySelectorAll("#allInp > .inp"); let result=0; let qarz=0; for(let i=0;i<inp.length;i++){ let price=inp[i].getElementsByClassName("price")[0].value; let qnt=inp[i].getElementsByClassName("quantity")[0].value; [0].value; result+=(qnt*price); } counting(result) totalSumField() } {% extends 'base.html' %} {% load widget_tweaks %} {% block content %} <form method="POST">{% csrf_token %} {{items.management_form}} <div class="flex w-8/12 lg:w-9/12"> <div class=""> invoice number : </div> <div class="w-10/12 ml-8 border-b border-gray-600 border-dotted"> {{form.invoice_number | add_class:'bg-transparent w-full text-center focus:outline-none' }} </div> </div> <div class="w-full md:w-11/12 mx-auto realative p-2 bg-gray-200 invoice"> <!-- table --> <div class="mt-1 border border-black" style="direction: rtl;"> <!-- header --> <div class="flex flex-wrap grayBG text-sm text-white"> <div class="w-2/12 border-r text-center"> item </div> <div class="w-2/12 border-r text-center"> price </div> <div class="w-2/12 border-r text-center"> quantity </div> <div class="w-2/12 border-r text-center"> total price </div> </div> … -
Can I install PostgreSQL & PostGIS AFTER installing Django & GeoDjango?
I started following this tutorial2 after I failed with this one, tutorial1. I am trying to build this: Django is running after Django & GeoDjango installation. I am cautiously optimistic that I may have successfully installed GDAL v3.2.2, GEOS, and PROJ (worried that it is NOT PROJ.4). Next, I need to install PostgreSQL and its PostGIS extension. However, a lot of the instructions online warn that sequence of installation is important. I'm afraid to install PostgreSQL because I think it will break. This is the farthest I have gotten with the installation thus far and am afraid that I am building a house of cards that can fall at any time (due to my own lack of understanding). Do I proceed? Or should I just start over again from the start with a PostgreSQL installation and build fresh from there? Having learned that most of the trouble stems from those GIS packages, there is hope that I could now succeed. Hope is tenuous. Maybe I could just abandon PostgreSQL and run SQLite (except that appears to also require PROJ.4). The specs here say that I need PROJ4 (not PROJ) to work with PostgreSQL. But, PROJ might be the newer version … -
Django category model used in multiple models (belongs_to)
I have one Category model that I'd like to use in other models instead of creating different models for each case. Each model (Page, Article,...) has its own set of categories. Ex. Category model Page model with belongs_to category (page cat 1, page cat 2) Article model with belongs_to category (article cat 1, article cat 2) I can't use a polymorphic relationship since I don't have to store the id. So how can I represent that in my models? -
User authentication will not work in django
I have been trying to add user authentication to my social media/blog app in django. This code returns an error "UNIQUE constraint failed: auth_user.username". Can someone please tell me what I am doing wrong? Any helpful advice would be great. from django.shortcuts import render from django.http import HttpResponse from .forms import SignUpForm from django.contrib.auth.models import User def sign_up(request): context = {"form": SignUpForm} if request.method == "POST": form = SignUpForm(request.POST) if form.is_valid(): username = form.cleaned_data.get("username") email = form.cleaned_data.get("email") password = form.cleaned_data.get("password") user = User.objects.create(username=username, email=email, password=password) user = form.save(commit=False) else: form = SignUpForm() return render(request, "sign_up/sign_up.html", context) -
Django custom login form will not validate against is_valid()
Summary: My custom login form is failing to validate against .is_valid(). I have been able to confirm the email & password values are being passed through to views.py as print(request.POST.get('') returns both the email (required for login) and the password. I think my issue is different from other similar questions because they all seem to address missing required fields. I tried excluding every field I could think of from .is_valid but the form won't validate. I click the button and nothing happens. I am using Django 3.7. accounts/forms.py class LoginForm(forms.Form): email = forms.EmailField(label='email', max_length='255') password = forms.CharField(label='password') def __init__(self, request, *args, **kwargs): self.request = request super(LoginForm, self).__init__(*args, **kwargs) def form_valid(self, form): form.save() return super(LoginForm, self).form_valid(form) accounts/views.py I can't access anything inside the "form.is_valid" if statement. I pop out on the else: side. def login_page(request): if request.method == 'POST': #create form instance / populate form = LoginForm(request.POST) context = { "email": "email", "password": "password", "first_name": "first_name", "last_name": "last_name", "is_active": "is_active", "form": form } if form.is_valid(): username = form.cleaned_data.get("email") password = form.cleaned_data.get("password") user = authenticate(request, username=username, password=password) form.save() if user is not None: if user.is_active: login(request, user) print(request.is_authenticated()) context['form'] = LoginForm() return redirect('/') else: pass else: pass else: '''This is where I … -
Adding django-modeltranslation to existing project ruins tests
I have existing project and I decided to add translations options. I installed django-modeltranslation, added languages to settings, models to translation.py and added models in admin.py. from modeltranslation.translator import translator, TranslationOptions from .models import GameTask class GameTaskTranslationOptions(TranslationOptions): fields =('name', 'description', 'button_text') translator.register(GameTask, GameTaskTranslationOptions) @admin.register(GameTask) class GameTaskAdmin(TranslationAdmin): model = GameTask But as I mentioned I added it to existing project. So I have to move my existing data to created fields. So after makemigrations but before migrate I added to my migration file: def populate_function(apps, schema_editor): management.call_command("update_translation_fields") class Migration(migrations.Migration): dependencies = [ ('pages', '0054_auto_20210105_1041'), ] operations = [ ........., migrations.RunPython(populate_function, migrations.RunPython.noop), ] After that I run python manage.py migrate pages migrate_file. And it works. I have my database updated and my data aren't lost, they are moved to default language field set in settings. But after running my test I get: django.db.utils.ProgrammingError: column pages_gametask.button_text_pl does not exist. LINE 1: ..._text_pl" = "pages_gametask"."button_text" WHERE ("pages_gam... ^ HINT: Perhaps you meant to reference the column "pages_gametask.button_text". So to sum up, I have what I wanted - I have fields for my languages in my database, data aren't lost, but look like during test, the default database can't create due to language's fields. Can …