Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Related Field got invalid lookup: icontains with search_fields
I am trying to add a related field with a Many-to-Many relationship, but I am getting this error : Related Field got invalid lookup: icontains This is my View : class PostList(generics.ListCreateAPIView): """Blog post lists""" queryset = Post.objects.all() serializer_class = serializers.PostSerializer authentication_classes = (JWTAuthentication,) permission_classes = (PostsProtectOrReadOnly, IsMentorOnly) filter_backends = [filters.SearchFilter] search_fields = ['title', 'body', 'tags'] Then my models : class Post(TimeStampedModel, models.Model): """Post model.""" title = models.CharField(_('Title'), max_length=100, blank=False, null=False) # TODO: Add image upload. image = models.ImageField(_('Image'), upload_to='blog_images', null=True, max_length=900) body = models.TextField(_('Body'), blank=False) description = models.CharField(_('Description'), max_length=400, blank=True, null=True) slug = models.SlugField(default=uuid.uuid4(), unique=True, max_length=100) owner = models.ForeignKey(User, related_name='posts', on_delete=models.CASCADE) bookmarks = models.ManyToManyField(User, related_name='bookmarks', default=None, blank=True) address_views = models.ManyToManyField(CustomIPAddress, related_name='address_views', default=None, blank=True) likes = models.ManyToManyField(User, related_name='likes', default=None, blank=True, ) then the tags model : class Tag(models.Model): """Tags model.""" name = models.CharField(max_length=100, blank=False, default='') owner = models.ForeignKey(User, related_name='tags_owner', on_delete=models.CASCADE) posts = models.ManyToManyField(Post, related_name='tags', blank=True) class Meta: verbose_name_plural = 'tags' -
XAMPP MySQL cannot start
Xampp mysql phpmyadmin was running perfectly a few days ago. But now it's has this problem. I have tried stop the mysql in service.msc, i have tried to chang the port. I have tried to run XAMPP as administrator. But it's still not work. Could if because of a django project i've just installed? if that so, how do i fix it? enter image description here -
AWS Beanstalk Deployment Failing Due to WSGIPath
I'm trying to deploy a Django application the AWS ElasticBeanstalk. However, my deployments are failing due to a possible error in WSGIPath. Here is my configuration in /.ebextensions: option_settings: "aws:elasticbeanstalk:application:environment": DJANGO_SETTINGS_MODULE: "conf.settings" "PYTHONPATH": "/var/app/current:$PYTHONPATH" "aws:elasticbeanstalk:container:python": WSGIPath: conf.wsgi:application NumProcesses: 1 NumThreads: 15 Here is the error that I encounter: /var/log/web.stdout.log ---------------------------------------- Oct 28 04:17:54 ip-172-31-9-159 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker Oct 28 04:17:54 ip-172-31-9-159 web: worker.init_process() Oct 28 04:17:54 ip-172-31-9-159 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/gunicorn/workers/gthread.py", line 92, in init_process Oct 28 04:17:54 ip-172-31-9-159 web: super().init_process() Oct 28 04:17:54 ip-172-31-9-159 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/gunicorn/workers/base.py", line 134, in init_process Oct 28 04:17:54 ip-172-31-9-159 web: self.load_wsgi() Oct 28 04:17:54 ip-172-31-9-159 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi Oct 28 04:17:54 ip-172-31-9-159 web: self.wsgi = self.app.wsgi() Oct 28 04:17:54 ip-172-31-9-159 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/gunicorn/app/base.py", line 67, in wsgi Oct 28 04:17:54 ip-172-31-9-159 web: self.callable = self.load() Oct 28 04:17:54 ip-172-31-9-159 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 58, in load Oct 28 04:17:54 ip-172-31-9-159 web: return self.load_wsgiapp() Oct 28 04:17:54 ip-172-31-9-159 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp Oct 28 04:17:54 ip-172-31-9-159 web: return util.import_app(self.app_uri) Oct 28 04:17:54 ip-172-31-9-159 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/gunicorn/util.py", line 363, in import_app Oct 28 04:17:54 ip-172-31-9-159 web: raise ImportError(msg % (module.rsplit(".", 1)[0], obj)) Oct 28 04:17:54 … -
Django Asyncronous task running syncronously with asgiref
I'm receiving notification via API and I should return HTTP 200 before 500 milliseconds. I'm using asgiref library for it, everything runs ok but I think is not actualy running asyncronously. Main viev In this view I receive the notificacions. I set 2 Print points to check timming in the server log. @csrf_exempt @api_view(('POST',)) @renderer_classes((TemplateHTMLRenderer, JSONRenderer)) def IncommingMeliNotifications(request): print('--------------------------- Received ---------------------') notificacion = json.loads(request.body) call_resource = async_to_sync(CallResource(notificacion)) print('--------------------------- Answered ---------------------') return Response({}, template_name='assessments.html', status=status.HTTP_200_OK) Secondary view After receiving the notification I call the secondary view CallResource, which I expect to run asyncronusly. def CallResource(notificacion): do things inside.... print('--------------------------- Secondary view ---------------------') return 'ok' Log results When I check the log, I always get the prints in the following order: print('--------------------------- Received ---------------------') print('--------------------------- Secondary view ---------------------') print('--------------------------- Answered ---------------------') But I suppose that the Secondary viewshould be the last to print, as: print('--------------------------- Received ---------------------') print('--------------------------- Answered ---------------------') print('--------------------------- Secondary view ---------------------') What am I missing here? Any clues welcome. Thanks in advance. -
django query is slow, but my sql query is fast
I have a very simple vie in my django application def notProjectsView(request): context = { 'projects':notProject.objects.all(), 'title':'Not Projects | Dark White Studios' } return render(request, 'not-projects.html', context) When I removed the context it ran fast, but it's a simple query and shouldn't be so long, the database also doesn't have a lot of records, it has 1 project and in the template I query project.notProjectImage.all which could cause an n+1 issue but I removed that part to test it and it was still slow Django debug toobar shows a ~50ms sql query while the actual request in the time tab is over 15 seconds -
Atomic Database Transactions in Django
I want to have atomic transactions on all the requests in the Django app. There is the following decorator to add an atomic transaction for one request, @transaction.atomic def create_user(request): .... but then, in this case, I'll have to use this decorator for all the APIs. I tried doing this in settings.py: DATABASES = { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'blah', 'USER': 'postgres', 'PASSWORD': 'blah', 'HOST': '0.0.0.0', 'PORT': '5432', 'ATOMIC_REQUESTS': True } But adding ATOMIC_REQUESTS does not seem to work in some cases. Is there any way so that I can apply atomic transactions for all APIs? -
Get percentage by category in Django
I'm struggling with the ORM, I need to be able to get the percentage of the product(s) per category. A product has a foreign key of category. The ideal result would be: Category 1 = 20% Category 2 = 15.6% I was able to get the total per category but failed to get the percentage Product.objects.filter(category__isnull=False).annotate(percentage=Count("pk")).order_by("category__name") I might be able to solve this with Subquery but failed on multiple approaches. Any ideas? -
peerjs adding confirm to accept or refuse to coming call
I am developing a django project and including video call with using peerjs.So when user is calling on the other side confirm doesn't show.Can anyone help me ?(Actually the same code worked yesterday but today I didn't change anything nevertheless it isn't working now) var currentUserSlug = JSON.parse(document.getElementById('requestUserUsername').textContent); var other_user_slug = JSON.parse(document.getElementById('other_user').textContent); var video1=document.getElementById("video1"); var video2=document.getElementById("video2"); var camera=document.getElementById("camera"); var microfone=document.getElementById("microfone"); var isMicOpen=true; var isCamOpen=true; var side=window.location.search.substr(1).split("=")[1]; const peer = new Peer(currentUserSlug, { host: 'localhost', port: 9000, path: '/' }) navigator.mediaDevices.getUserMedia({audio:true,video:true}) .then(function(stream){ video2.srcObject=stream video2.play() video2.muted=true if(side=="caller"){ var call=peer.call(other_user_slug,stream) call.on("stream",function(remoteStream){ video1.srcObject=remoteStream video1.play() }) }else{ peer.on("call",function(call){ var resCall=confirm("Videocall incoming, do you want to accept it ?"); if(resCall){ call.answer(stream) call.on("stream",function(remoteStream){ video1.srcObject=remoteStream video1.play() }); } else{ console.log("declined."); } }) } }) -
Troubles extending from Django-Oscar AbstractUser model
I've been trying to fork django-oscar customer app. I've followed the guidelines on their documentation, but I can not apply migrations due to a ValueError: Related model 'customer.user' cannot be resolved. My project directory looks like this: project ├── config │ ├── asgi.py │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── customer │ ├── apps.py │ ├── __init__.py │ ├── migrations │ │ ├── 0001_initial.py │ │ ├── 0002_auto_20150807_1725.py │ │ ├── 0003_update_email_length.py │ │ ├── 0004_email_save.py │ │ ├── 0005_auto_20181115_1953.py │ │ ├── 0006_auto_20190430_1736.py │ │ ├── 0007_auto_20200801_0817.py │ │ ├── 0008_alter_productalert_id.py │ │ ├── 0009_user.py │ │ ├── __init__.py │ ├── models.py ├── manage.py Here are the steps I followed to arrive at the point I am now: ./manage.py oscar_fork_app customer . I added the customer app to my list of INSTALLED_APPS DJANGO_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "django.contrib.sites", "django.contrib.flatpages", ] PROJECT_APPS = [ "customer", # "customer.apps.CustomerConfig",, ] OSCAR_APPS = [ "oscar.config.Shop", "oscar.apps.analytics.apps.AnalyticsConfig", "oscar.apps.checkout.apps.CheckoutConfig", "oscar.apps.address.apps.AddressConfig", "oscar.apps.shipping.apps.ShippingConfig", "oscar.apps.catalogue.apps.CatalogueConfig", "oscar.apps.catalogue.reviews.apps.CatalogueReviewsConfig", "oscar.apps.communication.apps.CommunicationConfig", "oscar.apps.partner.apps.PartnerConfig", "oscar.apps.basket.apps.BasketConfig", "oscar.apps.payment.apps.PaymentConfig", "oscar.apps.offer.apps.OfferConfig", "oscar.apps.order.apps.OrderConfig", # "oscar.apps.customer.apps.CustomerConfig", "oscar.apps.search.apps.SearchConfig", "oscar.apps.voucher.apps.VoucherConfig", "oscar.apps.wishlists.apps.WishlistsConfig", "oscar.apps.dashboard.apps.DashboardConfig", "oscar.apps.dashboard.reports.apps.ReportsDashboardConfig", "oscar.apps.dashboard.users.apps.UsersDashboardConfig", "oscar.apps.dashboard.orders.apps.OrdersDashboardConfig", "oscar.apps.dashboard.catalogue.apps.CatalogueDashboardConfig", "oscar.apps.dashboard.offers.apps.OffersDashboardConfig", "oscar.apps.dashboard.partners.apps.PartnersDashboardConfig", "oscar.apps.dashboard.pages.apps.PagesDashboardConfig", "oscar.apps.dashboard.ranges.apps.RangesDashboardConfig", "oscar.apps.dashboard.reviews.apps.ReviewsDashboardConfig", "oscar.apps.dashboard.vouchers.apps.VouchersDashboardConfig", "oscar.apps.dashboard.communications.apps.CommunicationsDashboardConfig", "oscar.apps.dashboard.shipping.apps.ShippingDashboardConfig", ] INSTALLED_APPS = DJANGO_APPS + PROJECT_APPS + OSCAR_APPS … -
Error in django-helpdesk while applying command "python manage.py runserver"
ERRORS: helpdesk.KBItem.team: (fields.E300) Field defines a relation with model 'pinax_teams.Team', which is either not installed, or is abstract. helpdesk.KBItem.team: (fields.E307) The field helpdesk.KBItem.team was declared with a lazy reference to 'pinax_teams.team', but app 'pinax_teams' isn't -
How to get distinct values only from django database?
I have the following records in table I want to get all sender_id where receiver_id is 15 and all receiver_id where sender_id is 15. How can I define queryset. I have tried following def get_queryset(self): return Messages.objects.filter(Q(sender=15) | Q(receiver=15)) but this is giving me all the records but I want Distinct values only. simply I want to get all the receiver id's where sender is 15 and all sender ids where receiver is 15. here my expected output is 11,17. tell me how can I get these by defining query set. -
Django on IIS large file upload
I am trying to host a simple Django web application on a windows 10 machine with IIS 10 with FastCGI. As I my program is working with huge files, I would like to be able to upload large file (up to 10Gb). In my Django code, I already upload the files as chunks using this code: tmpFile = NamedTemporaryFile('w', delete=False) try: with tmpFile: for chunk in inputFasta.chunks(): tmpFile.write(chunk.decode("utf-8")) open(tmpFile.name, 'r') fastaSequences = SeqIO.parse(tmpFile.name, 'fasta') finally: os.unlink(tmpFile.name) but it is still not running. On my IIS, I adjusted the maxAllowedContentLength and maxRequestEntityAllowed to their respective maximum (maxAllowedContentLength: 2147483648, maxRequestEntityAllowed: 4294967295). Is there any other adjustment I can do? Or do I need another programm to help me doing it? My program works fine with smaller sized files. -
how can I write the admin panel in Django
I want to create a Django admin panel myself with this template like this admin panel How can I do this? -
Can I create a slug from two non-English fields using django-slugger?
I know about the module 'django-slugger'. I have the model Author with the fields 'firstname', 'lastname', but it'll contain Ukrainian symbols(non-English). I would like to have a slug with such a template: f"{firstname} {lastname}".title() Why do I need an English slug? Because I have such a URL "localhost/authors/<str::slug>". If the slug contains Ukrainian symbols, it might not work. -
HTTPSConnectionPool: Failed to establish a new connection: [Errno 111] Connection refused
I'm getting this error, not able to resolve it. HTTPSConnectionPool(host='api.github.com', port=443): Max retries exceeded with url: /repos/XXXX/XXXXX (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7fcf030252e8>: Failed to establish a new connection: [Errno 111] Connection refused',)) I'm fetching branch names from some repository with help of PyGithub. Everything is working when I run my web app with Gunicorn or by using the default Django webserver. But in production, it's not working & I'm getting the error mentioned above. -
Change class for CreateView Django
I have CreateView and I want add class for fields views.py: class CreatePost(CreateView): model = apps.blog.models.Post fields = ['name', 'content', 'photo'] template_name = 'cabinet/post/create.html' and in template: {% extends 'cabinet/includes/main.html' %} {% block title %}Створити новину{% endblock %} {% block content %} <form action="." method="POST"> {% csrf_token %} {{ form.media }} {{ form.as_ul }} </form> {% endblock %} And in output I have <p><label for="id_name">Name:</label> <input type="text" name="name" maxlength="250" required="" id="id_name"></p> but I want have <input type="text" name="name" maxlength="250" required="" class="form-control" id="id_name"> -
How to display custom Error 500 page with daphne in django
I have a problem with Daphne in Django. If the website throws an error 500, the default error 500 template from daphne is displayed. I´ve set up the error 500 handler exactly like the 404 handler, and the 404 handler works perfectly. If anyone knows how to fix this I´d be really thankful.If you should need more of the code, please just ask. Thanks in advance. urls.py handler404 = 'main.views.error_404' handler500 = 'main.views.error_500' views.py def error_404(response, exception=None): return render(response, "main/error_404.html", {}) def error_500(response): return render(response, "main/error_500.html", {}) -
Does Gorm support data migration?
I am starting a new project in golang and planning to use Gorm for my graphql project. I have some experience with Django and graphene-django. But due to performance issues, we decided to go with golang for the new project. But being new to golang, I am confused about a few things such as: Does Gorm support data migration as done in Django? Because I did google data migration in Gorm but couldn't find anything related to it. Refer here to know more about data migrations in Django. What are the pros and cons of Gorm and Django when compared as ORMs? PS: I have no issues with learning Golang as I was planning to do it anyways. -
Data is not filter in the search function in the Django
I'm trying to create search functionality in Django whenever user search the value in the label from the database and it return in the same page in table format. I received the data from an API and stored it in the database. I have created the search functionality but its not fetching the value all its shows the empty even the data available in the database. I don't know where I'm going wrong I have been trying a lot to resolve it. I want to show all the tables initially and then filter out through the search function. views.py def homeview(request): userb = Userbase.objects.all() table_data= requests.get('http://127.0.0.1:1500/api/').json() #api data saving in db for new_data in table_data: data = { 'region': new_data['region'], 'Area': new_data['area'], 'PBK_Desc': new_data['PBK_Desc'], } userb = Userbase.objects.create(**data) userb.save() if request.method == 'POST': finder = request.POST.get('PBK_Desc') invoiceuser = Userbase.objects.filter(PBK_Desc__icontains=finder) print(invoiceuser) print(finder) return render(request, 'home.html', {'invoiceuser':invoiceuser, 'finder':finder}) return render(request, 'home.html', {'userb':userb,'table_data':table_data}) html: <form action="" method="POST" autocomplete="off"> <div style="margin-left: 19px; font-size: 17px;">PBK Description</div> <div class="row" id="id_row"> <input type="text" name="PBK_Desc" maxlength="255" class="form-control mb-3" placeholder="PBK Description" id="PBK_Desc" required="" style="margin-left: 30px;"> </div> <br> <br> <input type="submit" value="Apply" id="btn_submit" style=" width:90px; height:45px; margin-left: 40px; margin-bottom: 30px;"class="btn btn-success btn"> <input type="reset" value="Reset" id="btn_submit" style=" width:90px; height:45px;margin-left: 65px; … -
Django show image button not functioning with for loop
My site allows users to upload bulk images. The issue is when a user is on mobile they could potentially have to scroll through 100's of images. I want to implement a show more button. I found this demo online that I got to work html: <div class="container"> <div class="grid"> <div class="cell"> <img src="https://i.natgeofe.com/n/3861de2a-04e6-45fd-aec8-02e7809f9d4e/02-cat-training-NationalGeographic_1484324.jpg" class="book" /> </div> <div class="cell"> <img src="https://i.natgeofe.com/n/3861de2a-04e6-45fd-aec8-02e7809f9d4e/02-cat-training-NationalGeographic_1484324.jpg" class="book" /> </div> </div> </div> <button onclick={showMore()}>Show all books</button> <script> const showMore = () => { document.querySelectorAll('.cell').forEach(c => c.style.display = 'block') } </script> css: @media screen and (min-width: 600px) { .container{ overflow: auto; height: (70vh); } .grid { display: flex; flex-wrap: wrap; flex-direction: row; } .cell { width: calc(50% - 2rem); } } .cell { margin: 1rem; } button { display: none; } @media screen and (max-width: 600px) { .cell { display: none; } .cell:first-child { display: block; } button { display: inline-block; } } However when I use the same code just with a for loop to display it does not work and just displays all the images. {% for images in postgallery %} <div class="container"> <div class="grid"> <div class="cell"> <img src="{{ images.images.url }}" class="book" /> </div> </div> </div> {% endfor %} <button onclick={showMore()}>Show all books</button> <script> const … -
integrating firebase video in django
I have stored video in Firebase storage. and its link is stored in Postgresql database through Django model, I'am not able to paly the video from the link in admin panel. It is showing error { "error": { "code": 400, "message": "Invalid HTTP method/URL pair." } } How to redirect from admin to firebase video link -
Django broken pipe when setting CORS
I want to connect flutter app with my Django API, but broken pipe keeps occuring. settings.py """ Django settings for crawler project. Generated by 'django-admin startproject' using Django 3.2.6. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-)4%#q5&d3^5=0!bauz62wxmc9csk*_c09k!jl2g1a-0rxsa--j' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crawling_data', 'rest_framework', 'corsheaders', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'crawler.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'crawler.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { … -
Django instance expected, got OrderedDict
Trying to manualette Model data and return to the client, have this error - TypeError: 'Location' instance expected, got OrderedDict class ParticipantViewSet(viewsets.ModelViewSet): def retrieve(self, request, pk=None): queryset = Participant.objects.all().prefetch_related("locations") user = get_object_or_404(queryset, pk=pk) serializer = ParticipantSerializer(user) locations = serializer.data["locations"] specialLocationList = locations index = 0 for location in locations: ## change location properties specialLocationList[index] = location index += 1 user.locations.set(specialLocationList) return JsonResponse(user, safe=False) -
Trying to deploy a django server with gunicorn, nginx, and docker
I'm trying to follow this, but I'm finding some issues. My folder structure is a follows: — project — config/nginx/conf.d — www — server — settings.py, wsgi.py, etc. — Dockerfile — manage.py — requirements.txt — docker-compose.yml — Dockerfile The most relevant files are as follows: Dockerfile FROM python:3 # Make the Python output not buffered; logs will show in real time ENV PYTHONUNBUFFERED=1 WORKDIR /www COPY requirements.txt /www/ RUN pip install -r requirements.txt COPY . /www/ EXPOSE 80 CMD ["gunicorn", "--bind", ":80", "server.wsgi:application"] docker-compose.yml version: "3.9" services: web: build: ./www volumes: - .:/web nginx: image: nginx:1.13 ports: - 80:80 volumes: - ./config/nginx/conf.d:/etc/nginx/conf.d depends_on: - web networks: - nginx_network networks: nginx_network: driver: bridge local.conf upstream www { server web:80; } server { listen 80; server_name localhost; location / { proxy_pass http://web; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } } This is the output I get: web_1 | [2021-10-28 14:44:43 +0000] [1] [INFO] Starting gunicorn 20.1.0 web_1 | [2021-10-28 14:44:43 +0000] [1] [INFO] Listening at: http://0.0.0.0:80 (1) web_1 | [2021-10-28 14:44:43 +0000] [1] [INFO] Using worker: sync web_1 | [2021-10-28 14:44:43 +0000] [7] [INFO] Booting worker with pid: 7 nginx_1 | 2021/10/28 14:44:46 [emerg] 1#1: host not found in upstream … -
ERROR: duplicate key value violates unique constraint already exists
I have Django app to maintain orders, products and etc. One order can have many OrderDetails, which stands for product related to the order. However when I try to add new OrderDetails instance aka assign product to order, I get this error. Database says such row already exists"(order_id, product_id)=(11076, 1)", which is not true if use a select query on this table. Order_id is One to one field and product_id is ForeignKey in django models, if that matters. "(order_id, product_id)=(11076, 1)" - This is a composite primary key. No serial or sequence is used here. If neededm here's some code class OrderDetails(models.Model): order = models.OneToOneField('Orders', models.DO_NOTHING, primary_key=True) product = models.ForeignKey('products.Products', models.DO_NOTHING) unit_price = models.FloatField() quantity = models.SmallIntegerField() discount = models.FloatField() class Meta: managed = False db_table = 'order_details' unique_together = (('order', 'product'),) def get_absolute_url(self): return u'/orders/%d' % self.order.pk class OrderDetailsCreateView(LoginRequiredMixin, CreateView): model = OrderDetails template_name = 'orders/orderdetails_create.html' form_class = OrderDetailCreateOrUpdateForm def get_form_kwargs(self, **kwargs): form_kwargs = super(OrderDetailsCreateView, self).get_form_kwargs(**kwargs) emp = get_current_users_employee(self.request.user) last_order = Orders.objects.filter(employee=emp, id=self.kwargs['pk'])[0] last_order_details = OrderDetails.objects.filter(order=last_order).values('product_id') already_selected_products = last_order_details form_kwargs['already_selected_products'] = already_selected_products return form_kwargs def form_valid(self, form): form.instance.order = Orders.objects.filter(employee=get_current_users_employee(self.request.user)).latest('id') return super(OrderDetailsCreateView, self).form_valid(form) Here's order_details table creation script: CREATE TABLE IF NOT EXISTS public.order_details ( order_id smallint NOT NULL, …