Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to remove the querysets '< [ <]>(code markers?)' for html (Django)
Am trying to just get a list of the made up gigs, (and hopefully make them links, to view them in a different html). Page result right now looks like this; <QuerySet [<Gig: Fulltime assistent needed from fall 2021!>, <Gig: Looking for event staff!>]> I don't know how to remove queryset 'code markers(or what are they called?)'. Just want the gig names listed. How can I fix that, to just show the gig titles? This is my code: Html: <div class="col"> {% if profile %} <div class="row justify-content-between"> <div class="col-9"> <p><b>My Gigs:</b></p> <p>{{profile.my_gigs}}</p> </div> <div class="col-3"> <p class="text-center"><b>No:</b></p> <p class="text-center"> {{profile.num_gigs}}</p> </div> <br> </div> {% endif %} </div> Views: def my_gigs(request): profile = Profileuser.objects.get(user=request.user) template = 'profileusers/my_gigs.html' context = { 'profile': profile, } return render(request, template, context) def create_gig(request): profile = Profileuser.objects.get(user=request.user) template = 'profileusers/create_gig.html' context = { 'profile': profile, } return render(request, template, context) Model: def my_gigs(self): return self.gig_set.all() @property def num_gigs(self): # pylint: disable=maybe-no-member return self.gig_set.all().count() -
django api for upload is very slow
My django api is soo slow when uploading files to a server, but very fast when using it on localhost. The api is supposed to receive files and save them to disk. I am expecting uploaded files to be between 70mb to about 600mb and save them in a storage. The files are binary files with a .svo extention created by stereolabs zed camera. Running this on localhost is very fast but when I deploy it to the server is becomes incredily slow. My internet speed is around 50mbps and the test file I am using is just 69mb. It takes over 24mins to upload the file, which is unacceptable. What could be the issue with why the uploading to the server is soo slow. This is my views.py to request and create a directory and save it import os import pathlib # external libraries from django.http import JsonResponse from rest_framework.views import APIView from django.core.files.storage import FileSystemStorage # environment variables from keys import USER_DIR # this is just a directory from .env class SaveRosBag(APIView): def post(self, request, *args, **kwargs): # integer_key & timestamp integer_key = self.kwargs['integer_key'] timestamp = self.kwargs['timestamp'] # required files if "zed_svo" in self.request.FILES: zed_svo = self.request.FILES["zed_svo"] else: … -
How to start Celery Beat with Supervisor
I am working on setting up Celery Beat with Supervisord. /etc/supervisor/conf.d/website.conf: [program:website-beat] command=bash /home/david/PycharmProjects/website/config/script.sh directory=/home/david/PycharmProjects/website user=www-data autostart=true autorestart=true stdout_logfile=/home/david/PycharmProjects/website/logs/celeryd.log [program:website] command=/home/david/PycharmProjects/website/venv/bin/celery -A config worker --loglevel=INFO -n worker1@%%h directory=/home/david/PycharmProjects/website user=www-data autostart=true autorestart=true stdout_logfile=/home/david/PycharmProjects/website/logs/celeryd.log redirect_stderr=true script.sh: #!/bin/bash cd /home/david/PycharmProjects/website/ source ../venv/bin/activate celery -A config beat -l info When I run sudo supervisorctl start all I get the output: website: started website-beat: ERROR (spawn error) When I run the script.sh file or celery -A config beat -l info manually, Celery Beat works. Thoughts on why this could be happening and how to fix it? -
Django how to use blocks in templates
Basicly my django project consists of the templates with html. I would like to fill the context of the site using blocks. My problem is that I would like to send the block to sidebar and the base part of the page from application's .html files. Templates: sidebar.html footer.html header.html base.html In my base.html I use: {% include 'partials/_sidebar.html' %} {% block content %}{% endblock %} in my sidebar.html I use {% block sidebar %}{% endblock %} and in my Application index.html i try to use: {% extends 'base.html' %} {% load static %} {% block content %} <h1>Home Page</h1> {% endblock %} {% block sidebar %} <div class="bg-white py-2 collapse-inner rounded"></div> <h6 class="collapse-header">Custom Components:</h6> <a class="collapse-item" href="{% url 'veggies' %}">veggies</a> <a class="collapse-item" href="{% url 'fruits' %}">fruits</a> </div> {% endblock %} But it is obviously not working. The starting page triggers app/index.html with a view. How to workaround such a problem? [i cant add post][1] [1]: https://i.stack.imgur.com/FV3Co.png -
I could not upload on wagtail admin when my project was deployed to Heroku
When I uploaded image files on wagtail, although it is going well to read image title but images itself was destroyed. so the titles is showed on the display of both admin and user side. I browsed through some blogs and websites on media and static, but this problem has not been resolved for almost three days. Development environment python==3.7.3 Django==3.2.6 gunicorn==20.1.0 psycopg2==2.9.1 wagtail==2.14 whitenoise==5.3.0 DB == postgres server == Heroku stack-18 my try and error ①added the follow code to urls.py python + static(settings.STATIC_URL, document_root=settings.STATICFILES_DIRS) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ②changed like follow application = get_wsgi_application() application = DjangoWhiteNoise(application) ↓ application = Cling(get_wsgi_application()) related code (those are possible to relate into this problem) #production.py from __future__ import absolute_import, unicode_literals import dj_database_url import os from .base import * #省略 STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' COMPRESS_OFFLINE = True COMPRESS_CSS_FILTERS = [ 'compressor.filters.css_default.CssAbsoluteFilter', 'compressor.filters.cssmin.CSSMinFilter', ] COMPRESS_CSS_HASHING_METHOD = 'content' #省略 #urls.py urlpatterns = [ path('django-admin/', admin.site.urls), path('admin/', include(wagtailadmin_urls)), ] + static(settings.STATIC_URL, document_root=settings.STATICFILES_DIRS) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) #wsgi.py import os from dj_static import Cling from django.core.wsgi import get_wsgi_application application = Cling(get_wsgi_application()) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "squjap.settings.production") #base.py MIDDLEWARE = [ 'whitenoise.middleware.WhiteNoiseMiddleware', ] STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(PROJECT_DIR, 'static')] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = … -
Django ModelAdmin get_urls not registering correctly
I'm trying to add a custom url and page to use to display certain data on the admin side of Django for a model of mine. Here is my code in admin.py class AdminUserEventHistory(admin.ModelAdmin): def get_urls(self): # get the default urls urls = super().get_urls() # define urls my_urls = [ path('userhistory/<int:pk>/>/', self.admin_site.admin_view(self.admin_user_event_view)) ] # make sure here you place the new url first then default urls return my_urls + urls def admin_user_event_view(self, request): context = {} context['history'] = None return HttpResponse('Success!') Then towards the bottom I register it with admin.site.register(EventAttendee, AdminUserEventHistory) The url should be /admin/events/eventattendee/userhistory/1/ if i'm not mistaken as I want it to take in the primary key of the user so I can pull info based on the user id. Sadly I am getting the following error. Event Attendee with ID “userhistory/1” doesn’t exist. Perhaps it was deleted? I do have two test records in that table and able to display them with the /admin/events/eventattendee/2/change. Did I miss something? This is all based on the Django documentation for 3.2 found here -
Django Circular Import Issue
so my django project was working completely fine and everything worked. I wanted to rename an app something else so I did and updated all the associated files in including the app.py config file. I also cleared the database and removed all migration files from each app. Ever since then I have never been able to finish makemigrations onto my apps. I even recreated the app I renamed, by doing django-admin startapp "appname" and then copied the contents of models.py admin.py, etc over to see if I somehow cause an internal issue but I just can't figure out what's going on?. I did manage to get all the makemigrations to success for all apps including the one I remade when I removed this (below) from another apps admin.py file # accounts/admin.py class SigBotSettingsInLine(admin.StackedInline): model = SigBotSettings @admin.register(Bot) class BotAdmin(admin.ModelAdmin,): ... inlines = [SigBotSettingsInLine] but in the end the python manage.py migrate, still Failed. If someone would help it would be highly appreciated. Here is the error-code: (dguacENV) PS C:\Users\Admin\Desktop\djangoProjects\dguac> python manage.py makemigrations accounts Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Admin\anaconda3\envs\dguacENV\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File … -
How to run periodic task using crontab inside docker container?
I'm building Django+Angular web application which is deployed on server using docker-compose. And I need to periodically run one django management command. I was searching SO a bit and tried following: docker-compose: version: '3.7' services: db: restart: always image: postgres:12-alpine environment: POSTGRES_DB: ${DB_NAME} POSTGRES_USER: ${DB_USER} POSTGRES_PASSWORD: ${DB_PASSWORD} ports: - "5432:5432" volumes: - ./db:/var/lib/postgresql/data api: restart: always image: registry.gitlab.com/*******/price_comparison_tool/backend:${CI_COMMIT_REF_NAME:-latest} build: ./backend ports: - "8000:8000" volumes: - ./backend:/code environment: - SUPERUSER_PASSWORD=******** - DB_HOST=db - DB_PORT=5432 - DB_NAME=price_tool - DB_USER=price_tool - DB_PASSWORD=********* depends_on: - db web: restart: always image: registry.gitlab.com/**********/price_comparison_tool/frontend:${CI_COMMIT_REF_NAME:-latest} build: context: ./frontend dockerfile: Dockerfile volumes: - .:/frontend ports: - "80:80" depends_on: - api volumes: backend: db: Dockerfile (backend): FROM python:3.8.3-alpine ENV PYTHONUNBUFFERED 1 RUN apk add postgresql-dev gcc python3-dev musl-dev && pip3 install psycopg2 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ ADD entrypoint.sh /entrypoint.sh ADD crontab_task /crontab_task ADD run_boto.sh /run_boto.sh RUN chmod a+x /entrypoint.sh RUN chmod a+x /run_boto.sh RUN /usr/bin/crontab /crontab_task RUN pip install -r requirements.txt ADD . /code/ RUN mkdir -p db RUN mkdir -p logs ENTRYPOINT ["/entrypoint.sh"] CMD ["gunicorn", "-w", "3", "--timeout", "300", "--bind", "0.0.0.0:8000", "--access-logfile", "-", "price_tool_project.wsgi> crontab_task: */1 * * * * /run_boto.sh > /proc/1/fd/1 2>/proc/1/fd/2 run_boto.sh: #!/bin/bash -e cd price_comparison_tool/backend/ python manage.py boto.py But when I … -
react doesnt see django localhost when loading images
Name: {item.name} <img src={item.photo} alt="description "></img> json: { "id": 9, "name": "name", "photo": "http://127.0.0.1:8000/media/image.jpg", } item.photo is loaded from django rest framework api and it returns: GET http://127.0.0.1:8000/media/image.jpg 404 (Not Found) ,item.name works normally. When i cut off "http://127.0.0.1:8000" from json image is displaying. How to reapair that? -
Django Get image from s3 bucket if image source is stored in a database
I have a model where users upload pictures to an s3 bucket. class Curso(models.Model): titulo = models.TextField() foto = models.ImageField(upload_to='media/cursos') #this goes to mybucket/media/cursos alt = models.TextField() ... It uploads fine to the s3 bucket but the source to the images gets stored in the database like "media/cursos/theimage.jpg" And I would like to display the images from the objects in a template like this <img class='curso__tarjeta--imagen' loading="lazy" src="{{curso.foto}}" alt={{curso.alt}}"> But it doesn't work because the path is not the whole path my s3 bucket My static tag is pointing to my s3 bucket. My question is: is there a way to do something like this -> {% load static %} <img class='curso__tarjeta--imagen' loading="lazy" src="{%static%}{{curso.foto}}" alt={{curso.alt}}"> I'm trying like that but it doesn't work! What should I do? Help! And thank you in advance -
DRF Pagination page_size not working with ModelViewSet
I am trying to use ModelViewSet and PageNumberPagination together but can't seem to get page_size working. I have set my size to 200 but it lists 200+ items always. Here is my code snippet: class ExamplePagination(pagination.PageNumberPagination): page_size = 200 max_page_size = 200 class VideosViewSet(viewsets.ModelViewSet): parser_classes = (FormParser, JSONParser) serializer_class = VideoSerializer pagination_class = ExamplePagination queryset = Video.objects.all() @swagger_auto_schema(responses={200: VideoSerializer}) def list(self, request): """ Request to list all videos """ queryset = Video.objects.all().order_by("-published_at") if queryset.exists(): page = self.paginate_queryset(queryset) if page is not None: serialized = VideoSerializer(queryset, many=True) return self.get_paginated_response(serialized.data) return Response(status=http_status.HTTP_404_NOT_FOUND) I tried everything from custom mixins to setting the page size in settings.py Here is my settings.py as well REST_FRAMEWORK = { "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination", 'PAGE_SIZE': 200, } -
Django serialize object return array
Django serialize object return an array, and i cant get it in template with js my view.py: def MyExempleView(request): data = serializers.serialize("json", myModel.objects.all()) context = { "data" : json.loads(data) } return render(request, 'consulta/myTemplateExemple.html', context=context) my template: {{ data|json_script:"data" }} if ($("#data").length) { var data= JSON.parse(document.getElementById('data').textContent); } my result exemple: "[{"key": "value"}, {"key2": "value2"}]" -
Django API for upload taking to long to upload files
I am working on a django rest api to upload 3 files and save it to disk. The files are [file.svo, file.db3 and file.yaml]. The code below works fine and fast when I test it locally. However, when I put it on a server the files it takes a really long time to upload the files. When I comment out the upload and saving the file.svo part from the code the upload run very fast. # in built libraries import os from time import sleep from pathlib import Path # external libraries import requests from django.http import JsonResponse from rest_framework.views import APIView from django.core.files.storage import FileSystemStorage # environment variables from keys import USER_DIR #this is a directory class SaveRosBag(APIView): def post(self, request, *args, **kwargs): # integer_key & timestamp integer_key = self.kwargs['integer_key'] timestamp = self.kwargs['timestamp'] # required files if "db3_file" in request.FILES: db3_file = self.request.FILES["db3_file"] else: return JsonResponse({"error":"KeyError [db3_file]"}) if "yaml_file" in request.FILES: yaml_file = self.request.FILES["yaml_file"] else: return JsonResponse({"error":"KeyError [yaml_file]"}) if "svo_file" in request.FILES: svo_file = self.request.FILES["svo_file"] else: return JsonResponse({"error":"KeyError [svo_file]"}) # make directory if it doesn't exit Path(os.path.join(USER_DIR, str(integer_key), str(timestamp), 'chdir') ).mkdir(parents=True,exist_ok=True) # define paths svo_folder = os.path.join(USER_DIR,str(integer_key),str(timestamp)) yaml_db3_folder = os.path.join(ride_folder,'chdir') # saving rosbag save_db3 = FileSystemStorage(location=yaml_db3_folder) save_db3.save(db3_file.name, db3_file) # … -
Execute a test with a django application on gilab
can someone please help me. I have problems to do test on gitlab with a django application. It's about connexion to the server, I've try with postgress or mysql but nothing!! -
How to get rid of python manage.py permission denied problem in Vs code?
I tried to run command "python manage.py runserver" in VS code but i always get this message: "bash: /c/Users/ACER/AppData/Local/Microsoft/WindowsApps/python: Permission denied" Python permission denied picture And also, i tried to run command "py manage.py runserver" still it does not run, instead it says: "Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases." py manage.py runserver pic -
Django EmailMessage.content_type = 'html' keep newlines?
How can I keep new lines in a Django's EmailMessage that has a content_type = 'html'? I need the html content type because of signatures. Email: Welcome User, this is a welcome email. Is rendered properly when sent as a text but when sent as an html, it (obviously) doesn't render newlines. Email: Welcome User,this is a welcome email. I'd like to have just a plain text in my templates but I'd like them to be converted into html with proper newlines. Is there a way to do that or do I need to write html tags myself? -
Show only the last form field in Django
I have form model with three fields but the template shows me only one : forms.py class ChooseAvailabilities(forms.Form): timeslots_day1 = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple, choices=TIMESLOT_LIST ), timeslots_day2 = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple, choices=TIMESLOT_LIST ) timeslots_day3 = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple, choices=TIMESLOT_LIST ) views.py def chooseAvailabilities(request): if request.method == "POST": form = ChooseAvailabilities(request.POST) if form.is_valid(): temp = form.cleaned_data.get("timeslots") print(temp) else: form = ChooseAvailabilities() return render(request, 'panel/choose_availabilities.html', {"form" : form}) choose_availabilities.html {% extends 'panel/base.html' %} {% block content %} <form method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit"> </form> {% endblock content %} It shows me only the checkbox field of timeslots_day3, I want also to see timeslots_day2 and timeslots_day1 I tried to show them one by one with this code : {% extends 'panel/base.html' %} {% block content %} {{ form.non_field_errors }} <div class="fieldWrapper"> {{ form.timeslots_day1.errors }} <label for="{{ form.timeslots_day1.id_for_label }}">timeslots_day1:</label> {{ form.timeslots_day1 }} {{ form.timeslots_day2.errors }} <label for="{{ form.timeslots_day2.id_for_label }}">timeslots_day2:</label> {{ form.timeslots_day2 }} {{ form.timeslots_day3.errors }} <label for="{{ form.timeslots_day3.id_for_label }}">timeslots_day3:</label> {{ form.timeslots_day3 }} </div> {% endblock content %} But It shows me this... : -
Is there anything I should be doing to protect my security when opening a port?
I'm new to this, so I apologize if my question is a little too simplistic or I don't have the correct understanding. I can't find anything in the django guide and I'm not sure if the general port information is the same considering what i'm doing with Django. I'm running a django runserver on '0.0.0.0:8000', which allows me to access the server remotely on another device in the same household. Is there anything I should be doing to help protect from outside attacks as the port is open? I believe I read that although this won't grant access to the device running the server, it can leave it vulnerable to issues. But there shouldn't be any sensitive data being transmitted as it's been used to enter data into a database. -
Django image background loading time
There is a latency when my website page loads between the display of all the differents elements composing the page and the display of the background image. I tried to drastically reduce the background image quality but no improvement in the loading time. Here is my CSS code for the background image: body { background: url("images/background.jpg") no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; background-attachment: fixed; } -
Cant navigate between different html pages in django
When i try to navigate from the home page to any other page is works just fine but trying to navigate from that other page back to the home page will just add home to the domain name which will give an error this is the html code <nav> <ul> <li><a href="">Home</a></li> <li><a href="./about">About</a></li> <li><a href="./pizza">pizzas</a></li> </ul> this the urls.py file from django.contrib import admin from django.urls import path from pizza_man import views urlpatterns = [ path('admin/', admin.site.urls), path('' , views.home_view , name='home' ,), path('about/' , views.about , name ='about'), path('pizza/' , views.show_pizza , name = 'pizza') ] what do i need to change to make this workout see the link -
How can i select some columns with or operator in views?
How can i select some columns with or operator in views.py? I want to run the below query in views.py in Django: SELECT name,family FROM student WHERE male = True OR degree=False I used this ORM: student = stu.objects.filter(male = True).values('name','family') | stu.objects.filter(degree = False).values('name','family') Is this correct? Is there a way that i can remove duplicate values('name','family') in query? -
Sending data from Django view to Django form
I have a Django view and I want to send the request data to a form. class PostDetailView(DetailView): model = Post form = CommentForm def get_form_kwargs(self): kwargs = super(PostDetailView, self).get_form_kwargs() kwargs['user'] = self.request.user.username return kwargs def post(self, request, *args, **kwargs): form = CommentForm(request.POST) if form.is_valid(): post = self.get_object() form.instance.user = request.user form.instance.post = post form.save() return redirect(reverse("post-detail", args=[post.pk])) from django import forms from .models import Comment from djrichtextfield.widgets import RichTextWidget class CommentForm(forms.ModelForm): user = forms.ChoiceField(required=True) def __init__(self, *args, **kwargs): self.user = kwargs.pop('user', None) super(CommentForm, self).__init__(*args, **kwargs) self.fields['user'].choices = self.user content = forms.CharField(widget=RichTextWidget(attrs={ 'class': 'md-textarea form-control', 'placeholder': 'Comment here ...', 'rows': '4', })) class Meta: model = Comment fields = ('author', 'content',) According to the docs, get_form_kwargs allows key-value pairs to be set in kwargs. The kwargs is then passed into the form. The form's init function should then be able to pick up the user value from kwargs. However, self.user returns None, and debugging showed that get_form_kwargs did not run at all. I have two questions: how do functions in view classes get executed? And what is the correct method to pass data from a view to a form? -
Django create dynamic url with unique id
I am working on a ecommerce project and trying to integrate a third party payment API. In the product checkout view I have something like the code below, where a payment id is generated. In future when customer has paid, I will receive a get call on my backend with this payment id and I need a way to recognize that and redirect that get call to payment confirmation page. class checkout(View): def get(self, request, *args, **kwargs): ... paymentId = call_thirdParty_for_payment_id(paymentDetails) ... #The returned paymentId id is alphanumeric. Is there a way to tell Django that in future if we receive a request containing this payment id in the url it should direct the request to payment confirmation page? return render(request, 'paymentUI.html') After the customer has paid I will receive a get call with a url like: https://www.example.com/payment?paymentId=xxxxxxxx Right now my backend respond with an error as it does not know how to handle that get call. -
Django model property is not working - Django
I'm facing a issue with while trying to define a property in Django model and access them. I have 2 models first one is product and second one is product attributes. Product attributes has several field like Color and Brand. I want to create properties to get the product's brand and color for usage in template and filtering( django-filter) but property in model not giving result as expected. Please find the below codes and remarks for your reference and help. Product Model : class Product(models.Model): measurement_choices = (('Liter', 'Liter'), ('Kilogram', 'Kilogram'), ('Cloth', 'Cloth'), ('Shoe', 'Shoe')) name = models.CharField(max_length=200) sku = models.CharField(max_length=30, null=True) stock = models.CharField(max_length=10, null=True) measurement = models.CharField(choices=measurement_choices, max_length=20, null=True) description = models.CharField(max_length=10000) price = models.DecimalField(max_digits=7, decimal_places=2) discounted_price = models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True) image = models.ImageField(upload_to='product/images', default='product.png', null=True, blank=True) image_one = models.ImageField(upload_to='product/images', null=True, blank=True) image_two = models.ImageField(upload_to='product/images', null=True, blank=True) image_three = models.ImageField(upload_to='product/images', null=True, blank=True) image_four = models.ImageField(upload_to='product/images', null=True, blank=True) image_five = models.ImageField(upload_to='product/images', null=True, blank=True) tags = models.ManyToManyField(Tags) sub_category = models.ForeignKey(SubCategory, on_delete=models.SET_NULL, null=True,related_name='+') status = models.CharField(max_length=20, choices=(('Active', 'Active'), ('Inactive', 'Inactive'))) history = HistoricalRecords() Property i have created to get the brand name: def p_brand(self): brand = '' all_attributes = self.productattribute_set.all() for att in all_attributes: brand = att.brand.title print(brand) return brand … -
django e postgres"DETAIL: Key (field)=() is duplicated"
i been makein migrations in my database, and i received this error: (env)$ python manage.py migrate System check identified some issues: Operations to perform: Apply all migrations: account, admin, auth, contenttypes, models, sessions, sites, socialaccount Running migrations: Applying models.0018_auto_20210809_1124...Traceback (most recent call last): File "/home/lucas/MaxiLimpService/env/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UniqueViolation: could not create unique index "models_funcionario_cpf_funcionario_d9311e70_uniq" DETAIL: Key (cpf_funcionario)=() is duplicated. The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/lucas/MaxiLimpService/env/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/lucas/MaxiLimpService/env/lib/python3.8/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/lucas/MaxiLimpService/env/lib/python3.8/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/home/lucas/MaxiLimpService/env/lib/python3.8/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/home/lucas/MaxiLimpService/env/lib/python3.8/site-packages/django/core/management/base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "/home/lucas/MaxiLimpService/env/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 244, in handle post_migrate_state = executor.migrate( File "/home/lucas/MaxiLimpService/env/lib/python3.8/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/home/lucas/MaxiLimpService/env/lib/python3.8/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/home/lucas/MaxiLimpService/env/lib/python3.8/site-packages/django/db/migrations/executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) File "/home/lucas/MaxiLimpService/env/lib/python3.8/site-packages/django/db/migrations/migration.py", line 126, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/home/lucas/MaxiLimpService/env/lib/python3.8/site-packages/django/db/migrations/operations/fields.py", line 244, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File …