Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Clickable EDIT button inside a popup window and on clicking the button it performs action
I have created a simple page. In that I have a VIEW button so on clicking that view button I am able to open a popup window. So I want a button called "EDIT" to be inside the popup window and on clicking that EDIT button it should edit the JSON data which is coming from the URL in the popup window. ** This is my Base.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Operations Performed</title> <script> function calc() { var n1 = parseFloat(document.getElementById('n1').value); var n2 = parseFloat(document.getElementById('n2').value); var oper = document.getElementById('operators').value; if (oper === '+') { document.getElementById('result').value = n1+n2; } if (oper === '-') { document.getElementById('result').value = n1-n2; } if (oper === '*') { document.getElementById('result').value = n1*n2; } if (oper === '/') { document.getElementById('result').value = n1/n2; } } </script> </head> <body bgcolor='cyan'> {% block content %} {% endblock %} </body> </html> ** This is my Home.html {% extends 'base.html' %} {% load static%} {% block content %} <h1>Hello {{name}}...!!!></h1> <form action="add" method="POST"> {% csrf_token %} <select id="operators"> <option value="+">Addition</option> <option value="-">Subtraction</option> <option value="*">Multiplication</option> <option value="/">Division</option> </select><br> <br> <br> <br> <br> Enter 1st no: <input type="text" name="num1" value='{{val1}}' id="n1"><br> Enter 2nd no: <input … -
Django: Getting FieldError While Using Slug in URL
I am a beginner in Django. Right now, I am building an app, called PhoneReview. It will store reviews related to the latest mobile phone. It will also display phone brands, along with the associated phone models and their reviews. Right now, I am trying to use slug in URLs. I have successfully used slug in two of my templates, which are index.html and phonemodel.html. However, I am facing issues with the third template, which is details.html. When I go to http://127.0.0.1:8000/index, I see this page: When I click on Samsung, I see this page: Up to this is fine. But when I click on any phone model, like Galaxy S10, I get FieldError error. It looks like this: FieldError at /details/galaxy-note-10 Cannot resolve keyword 'slug' into field. Choices are: date_published, id, link, phone_model, review_article When I click on Samsung, I am supposed to see the details.html page, which has the review of the phone, along with the news link. Instead, I am getting the 404 error. Here are my codes of models.py located inside PhoneReview folder: from django.db import models from django.template.defaultfilters import slugify # Create your models here. class Brand(models.Model): brand_name = models.CharField(max_length=100) origin = models.CharField(max_length=100) manufacturing_since = … -
Bootsrap collapse not working in Jinja template
I need to add multiple rows of data from backend to a table and toggle the div in which the table belongs onclicking the parent div of the div in which the table belongs. So I included a for loop in jinja template and after doing this bootstrap collapse doesn't seems to work and when i click over the heading the table div collapses but opens again ? Following is the jinja template : {% if leads.get_shortlisted_colleges %} <div class="card"> <div class="card-header"> <h5 class="card-title">Shortlisted Colleges</h5> </div> <div class="card-body"> {% for institute in leads.get_shortlisted_colleges %} <div class="box"> <div class="row"> <div class="col-xl-6"> <h1>{%if institute.institute%}{{institute.institute.name}}{% endif %} <a href="#" class="moreinfoinstitute" data-toggle="modal" data-institute8-id="{{institute.id}}" data-target=".clg-detail">More Info</a></h1> <p>{% if institute.institute.city %}{{institute.institute.city.name}},{% endif %} {%if institute.institute.state %}{{institute.institute.state.name}}{% endif %}</p> <p> L3 Assigned : <strong> {% if l3_assign_to %} {{l3_assign_to}} {% else %} None {% endif %} </strong> | Status : <span class="badge badge-pill badge-secondary"> {%if institute.status%} {{institute.status.name}} {% endif %} </span> | CAF : <a href="#">Not Available </a> </p> </div> <div class="col-xl-6 detail-btn text-right"> <button class="btn btn-outline-dark btn-sm viewtrail" data-toggle="modal" data-institute-id="{{institute.id}}" data-lead-id = "{{leads.id}}" data-target=".trail">View Trail</button> <button class="btn btn-outline-dark btn-sm visitcampus" data-toggle="modal" data-institute2-id="{{institute.id}}" data-target=".visit-campus">Visit Campus</button> <a href="#" class="btn btn-primary btn-sm">User Form Details</a> <button class="btn btn-danger btn-sm updatestatus" … -
Error when I upload.csv file in Django Admin
I get an sqlite3.IntegrityError: NOT NULL constraint failed: stores_product.quantity when I try to upload a csv in Django Admin panel this is my csv file Here is my admin.py file from django.contrib import admin from .models import Product from import_export.admin import ImportExportModelAdmin @admin.register(Product) class ViewAdmin(ImportExportModelAdmin): pass Here is the error Line number: 1 - NOT NULL constraint failed: stores_product.quantity , Oreo Biscuits, Cadbury, 100, 20, Cookies, 5 -
How to autocomplete input in field Django
I have a product model. I need to autocomplete product name into input field. class Product(models.Model): product_name = models.CharField(max_length=255) product_detail = models.TextField(blank=True, null=True) product_price = models.FloatField(blank=True) category = models.CharField(max_length=30) product_image = models.ImageField(upload_to='pictures/%Y/%m/%d/', max_length=255, blank=True, null=True) product_amount = models.IntegerField(blank=True, null=True) del_flag = models.BooleanField(default=False) def __str__(self): return self.product_name -
Django View Contained Within Template
This is hard to explain, but what I want to be able to do is have a search view which operates independently from all of my other views. I would like to have multiple templates with a search box embedded which will search and return results independent of the view that is being rendered. At the moment the only way I can think of to do this is to create a separate form instance for every single function based view. I would like to have the search self contained. Can someone advise me on what I need to look at to do this as I have no idea where to start. I was looking at class based vies, but I still can't separate the search function from the template. -
On executing python manage,py runserver is not showing any output on terminal
While executing python manage.py runserver is not showing any output on terminal and process exist without showing any error. Don't know how to fix it ??. I am new to djano. -
Use Rosetta on production site
We are looking for a way to help users translate our website. As developers, we sometimes edit the .PO files manually, but we also love Rosetta. The UI for Rosetta would also suit our translators. Is Rosetta also intended for use in a production environment by external users? Are there any examples of Rosetta running on a production site? If so, what strategy do you use to get the translations back into your repository? -
pip install django mysqlclient 'path should be string, bytes, os.PathLike or integer, not NoneType' on windows
I am new in python and django and want to install mysqlclient on windows.When command pip install django mysqlclient in cmd it throws this error : File "d:\myprojects\python\mytestdjangoprj\myproject\lib\genericpath.py", line 30, in isfile st = os.stat(path) TypeError: stat: path should be string, bytes, os.PathLike or integer, not NoneType please help me. -
How to Sort a Django ListView on Button Click
I'm making a website which has a bunch of Event posts (Parties, Get-Togethers, Fundraisers etc.). I want the user to be able to sort the posts by the date those event posts were created (created_date) and by the date that event post takes place (start_date) on button click. There are exactly 2 ways the user can sort the ListView (by created_date or by start_date according to my models.py) so I want the button to be a toggle, where clicking it once would filter by start_date and clicking the button once more (after the page refreshes) would filter by created_date. My home.html contains the button and a for loop to show the posts: <!-- THE EVENT FEED --> <div class="feed"> <h2>Event Feed</h2> <!--BUTTON TO FILTER EVENT FEED--> <div style = "border-top: solid 1px #eee; width:100%;align-items: center;display: flex;flex-direction: column;"> <a href="{% url 'whsapp-home' %}?ordering={% if ordering == 'created_date' %}-start_date{% else %}-created_date{% endif %}"><button>Filter by Event Date</button></a> <!--<button data-text-swap="Filter by Event Date"></button>--> </div> <div class="chat"> {% for post in posts %} <div class="your messages"> <div class="message"> <b>{{ post.title}}</b> </div> </div> {% endfor %} </div> </div> And here is my class based view for the posts: class PostListView(ListView): model = Post template_name = 'whsapp/home.html' … -
If you see valid patterns in the file then the issue is probably caused by a circular import
'C:\Users\huihuiqian\mys ite\posts\urls.py'>' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. mysite.urls.py from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^posts/', include('posts.urls')), ] post.urls.py from django.conf.urls import url from . import views urlpartterns =[ url(r'^$',views.index, name='index') ]; -
Searching in Django, a few words in one object
I have an app where a user can look for recipes by inputing ingredients. I am wondering how to make it in query that django will know that "Juice of lemon" is one ingredient, now after inputing "Juice of Lemon" it shows as well "Juice of citron". So when a user input "juice" it should show all ingredients which contains juice, but when a user will input whole ingredient name "Juice of citron" it should show only recipes containing this ingredient. def search_results(besos): query = besos.GET.get('q') q = Q() for queries in query.split(): q |= (Q(ingredients__ingredient_name__contains=queries)) results = Recipe.objects.filter(q) template = "drinks/search_results.html" context = { 'results' : results, } return render(besos, template, context) Models: class Ingredient(models.Model): ingredient_name = models.CharField(max_length=250) def __str__(self): return self.ingredient_name class Recipe(models.Model): recipe_name = models.CharField(max_length=250) preparation = models.CharField(max_length=1000) ingredients = models.ManyToManyField(Ingredient) -
Search results are not being displayed
I have created a model named Product consisting of these fields ('prod_name', 'company', 'quantity', 'price', 'units', 'prod_type'), so whenever I use the search bar to search the name of the company it doesn't display the products Here is my views.py file(contains only the search view) from django.shortcuts import render, redirect, get_object_or_404 from django.views.generic import TemplateView, ListView from django.db.models import Q from .models import * from .forms import * class SearchResultsView(ListView): model = Product template_name = 'search_results.html' def get_queryset(self): query = self.request.GET.get('q') items=Product.objects.filter(Q(company__icontains=query)) return items base.html file containing the searchbar <form class="form-inline my-2 my-md-0" action="{% url 'search_results' %}" method="get"> <input class="form-control" name="q" type="text" placeholder="Search"> </form> search_results.html file {% extends 'base.html' %} {% block body %} <br> <br> <table class="table table-hover"> <thead> <tr> <th>Sr. No.</th> <th>Product Name</th> <th>Company</th> <th>Quantity</th> <th>Price</th> <th>Units</th> <th>Product Type</th> </tr> </thead> <tbody> {% for item in items %} <tr> <td>{{item.pk}}</td> <td>{{item.prod_name}}</td> <td>{{item.company}}</td> <td>{{item.quantity}}</td> <td>{{item.price}}</td> <td>{{item.units}}</td> <td>{{item.prod_type}}</td> </tr> {% endfor %} </tbody> </table> {% endblock %} urls.py file from django.conf.urls import url from django.urls import path from .views import * urlpatterns=[ path('search/', SearchResultsView.as_view(), name='search_results'), ] Here's how it looks once I search for something -
Django contact form: display users email as sender in mailbox
I have got a contact form on my website where the user enters his/her email, a subject and a message. This is how my contact view looks like: def contactView(request): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] from_email = form.cleaned_data['from_email'] message = form.cleaned_data['message'] try: send_mail(subject, message, from_email, ['my.name@mydomain.com']) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('success') return render(request, "account/contact.html", {'form': form}) And these are my E-Mail settings: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'my.name@mydomain.com' EMAIL_HOST_PASSWORD = **************** EMAIL_PORT = 587 Everything works fine and I get an email from my.name@mydomain.com to my.name@mydomain.com with the subject and message. But I don't see the users email to reply. I can append it to the message but is there a way to change the senders email to the users email so that I can respond by clicking reply in my mailbox? -
KeyError: 'video_fps' with moviepy ffmpeg
I am writing a Python script to convert a video (.MP4) into an audio file (.MP3) on a Django server. To achieve this, I am using the Moviepy library but when I run the script, I get the following error: Internal Server Error: /test/ Traceback (most recent call last): File "C:\Users\etsho\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\etsho\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\etsho\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\etsho\AppData\Local\Programs\Python\Python38\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\shoe\musicsite\main\views.py", line 29, in test video = VideoFileClip(os.path.join(basePath + ".mp4")) File "C:\Users\etsho\AppData\Local\Programs\Python\Python38\lib\site-packages\moviepy\video\io\VideoFileClip.py", line 88, in init self.reader = FFMPEG_VideoReader(filename, pix_fmt=pix_fmt, File "C:\Users\etsho\AppData\Local\Programs\Python\Python38\lib\site-packages\moviepy\video\io\ffmpeg_reader.py", line 34, in init self.fps = infos['video_fps'] KeyError: 'video_fps' [15/Nov/2019 23:49:43] "POST /test/ HTTP/1.1" 500 80909 There's practically no information about this error or how to solve it that I could find, so any help or insight would be much appreciated. Here is my Python script (views.py): import pyodbc, json, pytube from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from rest_framework import parsers import os from moviepy.editor import * @csrf_exempt def test(request): if request.method == 'POST': filePath = 'C:\\Users\\etsho\\Music\\' #retrieve url from app body_unicode = request.body.decode('utf-8') body = json.loads(body_unicode) … -
where should i add the csrf token in this?
i really don`t understand what most of this html does as i am not comfortable with html. along with the location of where to add the token if one could explain to me what most of this does it would be greatly appreciated <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Raleway"> <link rel="stylesheet" href="static/css/body.css"> <body> <div class="bgimg w3-display-container w3-text-black"> <div class="w3-display-middle w3-jumbo"> <button class=" w3-button w3-white">HSEA STOCK</button> </div> <div class="w3-display-topleft w3-container w3-xlarge "> <p><button onclick="document.getElementById('id01').style.display='block'" style="width:auto;">Login</button></p> </div> </div> <div id="id01" class="modal"> <form class="modal-content animate" action="/login" method="POST"> {% csrf_token %} <div class="imgcontainer"> <span onclick="document.getElementById('id01').style.display='none'" class="close" title="Close Modal">&times;</span> </div> <div class="container"> <label for="uname"><b>Username</b></label> <input type="text" placeholder="Enter Username" name="username" required <label for="psw"><b>Password</b></label> <input type="password" placeholder="Enter Password" name="passwword" required> <button type="submit">Login</button> <label> <input type="checkbox" checked="checked" name="remember"> Remember me </label> </div> <div class="container" style="background-color:#f1f1f1"> <button type="button" onclick="document.getElementById('id01').style.display='none'" class="cancelbtn">Cancel</button> <span class="psw">Forgot <a href="#">password?</a></span> </div> </form> </div> <script> // Get the modal var modal = document.getElementById('id01'); // When the user clicks anywhere outside of the modal, close it window.onclick = function(event) { if (event.target == modal) { modal.style.display = "none"; } } </script> </body> sorry if this seams very obvious but i did not make this page and i am having trouble adding … -
Django: User able to sign up in custom registration form even if the email address is already used by another user
In my web app, I have a custom registration and login form which I made using HTML/CSS and not Django's form.as_p and Bootstrap. I have the following code in views.py: def loginUser(request): logout(request) if request.POST: username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect('/dashboard/') #otherwise show the user an error message else: login_message = "Your username or password is incorrect." return render(request, 'Meetings/index.html', {'login_message': login_message}) return render(request, 'Meetings/index.html') def signUp(request): if request.POST: username = request.POST['username'] email = request.POST['email'] password = request.POST['password'] password_confirm = request.POST['password-confirm'] if(valid_form(username, email, password, password_confirm)): #create the new user user = CustomUser(name=username, email=email, username=username) user.set_password(password) user.save() user = authenticate(username=username, password=password) login(request, user) return redirect('/dashboard/') else: message = "Something went wrong." return render(request, 'Meetings/index.html', {'message': message}) return render(request, 'Meetings/index.html') I have a CustomUser model in models.py: from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): id = models.AutoField(primary_key=True) name = models.CharField(max_length=200, null=True) email = models.EmailField(max_length=70, null=True) password = models.CharField(max_length=50, null=True) When a user signs up, a CustomUser is created and they are logged in to the app. However, if another user signs up using an email address that is already taken by another existing user, they are … -
Make form fields wider in Django+Bootstrap
I was wondering how I can make the form inputs themselves take up the same portion of the second column; I want the labels to be in one column and the inputs to take up the same percentage of the second column Here is my code in my HTML template: <form method="POST" class="form mt-3 mb-3"> {% csrf_token %} {% for field in form %} <div class="form-group row"> <label for="{{ field.name }}" class="col-sm-4 col-form-label">{{ field.label_tag }}</label> <div class="col-sm-6"> {{ field }} </div> </div> {% endfor %} {% buttons %} <button type="submit" class="btn btn-success float-right mb-3"><i class="fa fa-plus" aria-hidden="true"></i> Create</button> {% endbuttons %} </form> -
Django Populate Dropdown Menu With Choices From Many To Many Database
I would like to populate my dropdown menu with records from the Subject table which is a many to many choices field that is populated with subjects by adding them manually from the admin page. A course can have many subjects such as "business" and "marketing". Code: https://dpaste.de/825n How would I do that with django-select2 or use a form with model select or multiple model select? https://docs.djangoproject.com/en/2.2/ref/forms/fields/#modelchoicefield https://docs.djangoproject.com/en/2.2/ref/forms/fields/#modelmultiplechoicefield https://django-select2.readthedocs.io/en/latest/ Or maybe I could do it with a for loop on the template? For loops I have tried but no luck: https://dpaste.de/5MVi Desired Result: https://imgur.com/a/Iw9lk6I Can someone please help me figure it out? I have been stuck for a while now. -
How do I use the input of one field in multiple places on a form?
I'm very new to Django, so please forgive me if I'm using some of the terminology incorrectly. In one of my templates, I'm trying to use a form that has multiple input fields. In this specific case, the value of the two fields will always be the same (userName and userID will always match if they are at this template) and I do not want to alter the form itself. For this reason, I want to customize the form in this template so that there is only one place for the user to provide input, and use that in both fields of the form so that the user doesn't need to type in their ID twice. This is the code fragment I'm currently using: <form method="post"> {% csrf_token %} <label>ID:</label> <input type="text" name="userID" id="userID" placeholder="Type your ID number here."> <input type="hidden" name="userName" id="userName" value=userID> <button type="submit">Login</button> </form> I know that the issue is with the "value=userID" bit, but I've been searching and I can't figure out how to use information from one input field in multiple places. How do I take the userID and submit it as the userName without requiring the user to input it twice? -
Django: what is the better way to get users info from models in view or template?
I have few django models and I want display some information the for several users in the template. Below are the models: class CustomUser(AbstractUser): def __str__(self): return self.email class Post(models.Model): author = models.ForeignKey(CustomUser,on_delete=models.CASCADE,) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) post_url = models.URLField(max_length = 200, blank = True) slug = models.SlugField(unique=True, blank=True) class subscription(models.Model): creator = models.ForeignKey(CustomUser,default=None, null=True,on_delete=models.CASCADE,related_name='creator',) booster = models.ForeignKey(CustomUser,default=None, null=True,on_delete=models.CASCADE,related_name='booster') sub_value = models.FloatField(blank = True) sub_id = models.TextField(blank = True) status = models.BooleanField(default=False) dateSubscribed = models.DateTimeField(default=timezone.now) dateSubscriptionEnded = models.DateTimeField(default=timezone.now) paymentCount = models.FloatField(default= 0) I want to pass few users to template and display how many posts and subscriptions each user has? I am wondering what is the best way to do it? Is better number of posts and subscribers information in the view and just pass those things to template or pass users get that information in the template? Thanks! -
Getting column from table as an array to using context_processor on webpage
I am trying to pull column data from DB table using a Django context_processor. This table column contains different versions of the primary data. So need to collect all versions and pass it as context to the html page. The context processor function is as below. I am able to get all the versions, but the format is weird. Any idea how to clean and only get the versions in an array? There are 2 versions currently Version1.9 and Version2.0 in the Column. context_processor.py def Version(request): value = ModelName.objects.values_list('version') if value: return { 'getVersion' : value } else: print("Unable to get Version") return { 'getVersion' : "" } Console Output: &lt;QuerySet [(&#39;Version1.9&#39;,), (&#39;Version2.0&#39;,), (&#39;Version1.9&#39;,), (&#39;Version2.0&#39;,)]&gt; -
Page not found (404) - The current path, editEstHab/, didn't match any of these
I have a problem when I want to update an existing object... in another project, I used a similar lines of code, but now, it doesn't work when I'm going to save the actual information... models.py class habitacion(models.Model): nroHabitacion = models.IntegerField(null=False) tipoHabitacion = models.CharField(max_length=70, null=True) tipoCama = models.ForeignKey(tipoCama, on_delete=models.CASCADE, blank=True, null=False) accesorios = models.CharField(max_length=70, null=True) precio = models.IntegerField(null=False) estado_habitacion = models.ForeignKey(estadoHab, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.tipoHabitacion forms.py class UpdateHabForm(forms.ModelForm): class Meta: model = habitacion fields = [ 'estado_habitacion' ] views.py def editHab(request,id_habitacion): # llamando datos de habitacion seleccionada hab = habitacion.objects.get(id=id_habitacion) if request.method == 'GET': form = UpdateHabForm(instance=hab) else: form = UpdateHabForm(request.POST, instance=hab) if form.is_valid(): form.save() context = { 'form' : form, 'hab' : hab } return render(request,"editEstHab.html",context) urls.py path('editEstHab/<id_habitacion>', views.editHab, name="editEstHab"), enter image description here the more stranger thing is... at the end says The current path, editEstHab/, didn't match any of these., but when I search on my project, the only time that I use editEstHab/ is in urls.py... So... help :( I don't have any clue about what is my mistake. -
SAXO Bank API ERROR json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) for
Hi I have been having a lot of problems trying to consume the api from SAXO Bank. Basically I am trying to achieve the GET request, however I am not very familiar with web api's. Instead of getting the data, I got this error instead : json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0). Below are my codes from flask import Flask, render_template, request import json import requests app = Flask(name) @app.route('/api', methods=['GET']) def temperature(): r = requests.get('https://gateway.saxobank.com/sim/openapi/port/v1/balances?AccountKey=Y8lhERGA9duVrD1IY-7cpA==&ClientKey=Y8lhERGA9duVrD1IY-7cpA==') json_object = r.json() return r.json(result) if name == 'main': app.run(debug=True) -
Broken migrations with Django sites framework to restrict URLs access
I want to share single code-base Django (2.2) over 2 URLs : foo.domain.ltd & bar.domain.ltd. on foo.domain.ltd: all the Django URLs are available on bar.domain.ltd: only some URLs are available, all other return 403 error I expected using the sites framework (django.contrib.sites) to reach this goal : 1 code base 2 domains configured in the sites framework 2 gunicorn instances with appropriate configuration : core.settings.foo with SITE_ID = 1 core.settings.bar with SITE_ID = 2 1 nginx server listening clients and forwarding requests to the appropriate gunicorn instance depending the xxx.domain.ltd used The issue I encountered is that sites framework looks like model oriented : You can associate models to one, two (…) sites. I try to set urls depending on the sites, but I broke the ./manage migrate tool… 1) Settings the sites framework to my project and a dualsite app to host associated code : core.settings : INSTALLED_APPS = [ # (…) "django.contrib.sites", "dualsite.apps.DualsiteConfig", ] core.settings.foo : from core.settings import * SITE_ID = 1 core.settings.bar : from core.settings import * SITE_ID = 2 dualsite.migration.0001_set_sites : from django.db import migrations def my_sites(apps, schema_editor): Site = apps.get_model("sites", "Site") initial_site = Site.objects.get(id=1) initial_site.domain = "foo.domain.ltd" initial_site.name = "foo" initial_site.save() Site.objects.create(domain="bar.domain.ltd", name="bar") class …