Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
File is not submitting correctly, nested objects Django Models
I am trying to create a method that will send a created Model object to the server, validate it and save it. But this Model has another Model nested in it. The Model that is nested in it has an image file that also needs to be validate, but everytime I submit it says that file is not a file and not the correct encoding type. Code async function createFile(input) { let response = await fetch(input); let data = await response.blob(); let metadata = { type: 'image/jpg' }; // let name = input.substring(input.lastIndexOf('/')+1,input.length); return new File([data], input, metadata); } const updated_items = async () => { let a = props.items for (let i = 0; i < a.length; i++) { let img = await createFile(props.items[i].cover) let newimg = { "lastModified": img.lastModified, "lastModifiedDate" : img.lastModifiedDate, "name" : img.name, "size" :img.size, "type": img.type } a[i].cover = img } return a } const onAddClick = async () => { const formData = new FormData(); let items = await updated_items() // formData.append('about', about); // formData.append('name', cname); // formData.append('worn',date); // items.forEach(item => { // formData.append(`items[]`, JSON.stringify(item)); // }); for (let pair of formData.entries()) { console.log(pair[0]+ ', ' + pair[1]); } // console.log(items) const data = … -
how to order docker compose executions?
I need to run my database in the first place, because when I do docker-compose up I got this error, because database isn't running yet: django.db.utils.OperationalError: connection to server at "db" (172.27.0.2), port 5432 failed: Connection refused test-task-web-1 | Is the server running on that host and accepting TCP/IP connections? Dockerfile: FROM python:3.11-alpine WORKDIR /usr/src/app COPY requirements.txt ./ RUN pip install -r requirements.txt COPY . . CMD ["python", "backend/manage.py", "runserver"] docker-compose: version: "3.9" services: db: image: postgres:15.4-alpine expose: - "5432" environment: POSTGRES_DB: referal-api POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres volumes: - ./data:/var/lib/postgresql/data web: build: context: . dockerfile: Dockerfile restart: always ports: - "8000:8000" depends_on: - db links: - db:db -
apscheduler Lost connection to my datatbase during runtime (Hosted app and database on digital ocean)
I have an app that uses apscheduler to excute jobs and the intervel of a job being excuted is 8 days. It was working fine for the first 2 weeks but on the next schdeualed run time all the jobs had the same error and from what I could tell they seem to have lost connection to the database although nothing has been changed ` Job "auto (trigger: interval[8 days, 0:00:00], next run at: 2023-08-22 23:29:16 UTC)" raised an exception Traceback (most recent call last): File "/workspace/.heroku/python/lib/python3.11/site-packages/django/db/backends/base/base.py", line 308, in _cursor return self._prepare_cursor(self.create_cursor(name)) ^^^^^^^^^^^^^^^^^^^^^^^^ File "/workspace/.heroku/python/lib/python3.11/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "/workspace/.heroku/python/lib/python3.11/site-packages/django/db/backends/postgresql/base.py", line 330, in create_cursor cursor = self.connection.cursor() ^^^^^^^^^^^^^^^^^^^^^^^^ psycopg2.InterfaceError: connection already closed The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/workspace/.heroku/python/lib/python3.11/site-packages/apscheduler/executors/base.py", line 125, in run_job retval = job.func(*job.args, **job.kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/workspace/main/automate.py", line 7, in auto client = Client.objects.get(CLIENT_ID = client_id) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/workspace/.heroku/python/lib/python3.11/site-packages/django/db/models/manager.py", line 87, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/workspace/.heroku/python/lib/python3.11/site-packages/django/db/models/query.py", line 633, in get num = len(clone) ^^^^^^^^^^ File "/workspace/.heroku/python/lib/python3.11/site-packages/django/db/models/query.py", line 380, in self._fetch_all() File "/workspace/.heroku/python/lib/python3.11/site-packages/django/db/models/query.py", line 1881, in _fetch_all self._result_cache = list(self._iterable_class(self)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/workspace/.heroku/python/lib/python3.11/site-packages/django/db/models/query.py", line 91, in iter … -
Django : computationally/data intensive website
I come from the world of object programming (C++, python...) and am currently switching to web programming (django). The websites I went to build are computationally and data intensive (like complex spreadsheets with a lot of math involved). I have a hard time understanding what databases are used for in web programming and more generally understanding the architecture of web apps (or say computationally intensive websites). Here is my understanding : Databases are only doing the persistence (in a very organised way, very much like how objects are organised in memory), not for computations? If computation is required on the data (and the computation is server-side), the data is first queried by django from the DB then loaded into a python "object" data model, then the computation happens in plain python and sent to the client thanks to django's templates? Am I right? Additionally, I expect the data to be loaded at the beginning of a session. Architecturally speaking, were in django should the query of the DB and deserialisation of the data be achieved? -
Is this legitimate way of overriding the default user model
I am overriding django's default user model . I tried to link the userprofile with the CustomUser model and added a receiver which will automatically create instance of profile model when user is created based on their role from django.db import models from django.contrib.auth.models import AbstractUser from django.dispatch import receiver from django.utils.translation import gettext_lazy as _ from .managers import CustomUserManager from django.db.models.signals import post_save # Create your models here. class CustomUser(AbstractUser): username = None email = models.EmailField(_("email"),primary_key=True,unique=True,blank=False,null=False) phone_number = models.CharField(max_length=10,null=False,blank=False) ROLE_CHOICES = ( ('ADMIN', 'ADMIN'), ('STUDENT','STUDENT'), ('TEACHER', 'TEACHER'), ('PRINCIPAL', 'PRINCIPAL'), ) role = models.CharField(choices=ROLE_CHOICES, blank=True,default='ADMIN',max_length=10) REQUIRED_FIELDS = ['phone_number','first_name','last_name'] USERNAME_FIELD = "email" objects = CustomUserManager() def __str__(self): return self.email class StudentProfile(models.Model): user = models.OneToOneField(CustomUser,on_delete=models.CASCADE) id = models.AutoField(primary_key=True,unique=True) merit = models.CharField(max_length=6,blank=True,null=True) def __str__(self): return self.user.email class TeacherProfile(models.Model): user = models.OneToOneField(CustomUser,on_delete=models.CASCADE) id = models.AutoField(primary_key=True,unique=True) salary = models.CharField(max_length=6,blank=True,null=True) education = models.CharField(max_length=100,blank=True,null=True) def __str__(self): return self.user.email class PrincipalProfile(models.Model): user = models.OneToOneField(CustomUser,on_delete=models.CASCADE) id = models.AutoField(primary_key=True,unique=True) salary = models.CharField(max_length=6,blank=True,null=True) education = models.CharField(max_length=100,blank=True,null=True) years_of_experience = models.IntegerField(null=True, blank=True) def __str__(self): return self.user.email @receiver(post_save, sender=CustomUser) def create_user_profile(sender, instance, created, **kwargs): if created: if instance.role == 'PRINCIPAL': PrincipalProfile.objects.create(user=instance) elif instance.role == 'STUDENT': StudentProfile.objects.create(user=instance) elif instance.role == 'TEACHER': TeacherProfile.objects.create(user=instance) else: pass else: print("Profile not created") As a newcomer to coding, I've crafted … -
Handling Django Migrations Folder Persistence in Azure App Service
I'm deploying a Django application on an Azure web app. As I've learned, Azure App Service is ephemeral, meaning I can't rely on files being persistent. While I've found solutions online on how to manage media files using Azure Storage, I'm unsure about how to handle other Django-specific directories, particularly the migrations folder. It seems imperative for Django to have access to this folder to conduct migrations properly. Can anyone guide me on the best approach to handle Django here? Or maybe handle azure? I'm surprised by the lack of online resources discussing best practices for this specific scenario. -
django simple JWT getting user ID from view level
I'm making a website. For the first time I decided to make an authorization with simpleJWT. Everything works fine but I don't know how can I get logged user id or just logged user object from view. @api_view(['GET']) def test(request): if request.method == 'GET': return Response({'id':request.user.id}) request.user.id return null even if I'm logged in this is my authorization from frontend export default function Login(){ const [username, setUsername] = useState(''); const [password, setPassword] = useState(''); const [loggedIn, setLoggedIn] = useState(localStorage.access_token ? true : false); const submit = async e => { e.preventDefault(); const user = { email: username, password: password }; const response = await fetch("http://localhost:8000/token/", { method: "POST", headers: { "Content-Type":"application/json", }, body: JSON.stringify(user), }) const data = await response.json(); localStorage.clear(); localStorage.setItem('access_token', data.access); localStorage.setItem('refresh_token', data.refresh); setLoggedIn(true); } return( ... some form ... ) } urls from rest_framework_simplejwt import views as jwt_views urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('accounts.urls')), path('api/', include('posts.urls')), path('token/', jwt_views.TokenObtainPairView.as_view(), name ='token_obtain_pair'), path('token/refresh/', jwt_views.TokenRefreshView.as_view(), name ='token_refresh'), ] how can I get user ID from view ? -
Is there any way to recover Streamfield data that was lost due to lack of migration?
As a Wagtail newbie, I pushed changes to StreamFields in my models (i.e., adding new block types) without creating Migrations, as specified in the docs. This resulted in a large loss of user data, and unfortunately there isn't a recent database backup. If I were to go digging in a copy of the current Postgres database, would I be able to find the lost user data in the version history somehow? I'm also open to any other suggestions about how to recover the lost data, if possible. -
Django Crispy Form Doesn't Include Model ID When Using `{% crispy form %}` Tag
I have a Django crispy form that I'm using to update an object. I need to use a helper as follows: # forms.py from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Div, ButtonHolder, Submit class QuestionForm(forms.ModelForm): class Meta: model = Question fields = ('type', 'instructions', 'required') def __init__(self, *args, **kwargs): self.helper = FormHelper() self.helper.form_tag = False self.helper.layout = Layout( Div( Div(*self.fields.keys(), css_class='form-group'), ButtonHolder( Submit('submit', 'Submit', css_class='btn-primary') ) ) ) And in my template I have the following: <form method='post' action=''> {% crispy form %} </form> My problem is that in the rendered HTML, there is no hidden field storing the ID of the Question being updated. What I expect to see is something like this: <input type="hidden" name="question-id" value="1" id="id_question-id"> This is strange. So I tried doing the following: <form method='post' action=''> {{ form | crispy }} </form> And this works. The hidden ID field is present in my HTML, and everything works perfectly. Unfortunately, this approach does not work with my form helper, which defeats the purpose of using crispy-forms. Why doesn't the ID field show up when I use the {% crispy form %} tag? -
Can't connect to MySQL server on 'localhost:3306' in dockerised Django app using docker-compose
I'm trying to build a Dockerized Django application with a MySQl database, but am unable to connect to the database when running docker-compose up My Dockerfile is: # Use the official Python image as the base image FROM python:3.10 # Set environment variables ENV PYTHONUNBUFFERED 1 # Set the working directory inside the container WORKDIR /app # Copy the requirements file and install dependencies COPY requirements.txt /app/ RUN pip install -r requirements.txt CMD ["sh", "-c", "python manage.py migrate"] # Copy the project files into the container COPY . /app/ And docker-compose.yml looks like: version: '3' services: db: image: mysql:8 ports: - "3306:3306" environment: - MYSQL_DATABASE='model_db' - MYSQL_USER='root' - MYSQL_PASSWORD='password' - MYSQL_ROOT_PASSWORD='password' - MYSQL_HOST='localhost' volumes: - /tmp/app/mysqld:/var/run/mysqld - ./db:/var/lib/mysql web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/app ports: - "8000:8000" depends_on: - db env_file: - .env I'm using a .env file to define environment variables, and it is: MYSQL_DATABASE=model_db MYSQL_USER=root MYSQL_PASSWORD=password MYSQL_ROOT_PASSWORD=password MYSQL_HOST=localhost These are then loaded to the app settings.py like this: BASE_DIR = Path(__file__).resolve().parent.parent env = environ.Env() if READ_DOT_ENV_FILE := env.bool("DJANGO_READ_DOT_ENV_FILE", default=True): # OS environment variables take precedence over variables from .env env.read_env(env_file=os.path.join(BASE_DIR, '.env')) MYSQL_DATABASE = env('MYSQL_DATABASE', default=None) MYSQL_USER = env('MYSQL_USER', default=None) MYSQL_PASSWORD = env('MYSQL_PASSWORD', default=None) … -
Django rendering {% csrf_token %} as string when I set innerHTML
I have a page in which I have created a modal. Now I'm creating form in the modal that can be generated dynamically on the basis of which button is clicked. I have this JS function that sets the model content with form data. function openModal(askField, platformName) { const modal = document.getElementById("modal"); const modalContent = modal.querySelector('.modal-content'); modalContent.innerHTML = ` <h2 class="m-2 text-xl font-semibold text-center">${platformName} Authorization</h2> <form class="p-2" method="post" action="/authorize/${platformName.toLowerCase()}"> {% csrf_token %} <div class="p-3 border border-gray-500 rounded-lg"> <div class="m-2 flex justify-start space-x-2"> <label class="font-bold" for="ask_field">${titleCase(askField.replace("_", " "))}</label> <input class="border" id="ask_field" name="ask_field" required> </div> <div class="flex justify-between"> <button class="px-4 rounded-lg text-white transition ease-in-out delay-150 bg-red-600 hover:-translate-y-1 hover:scale-110 hover:bg-indigo-500 duration-300" onclick="closeModal()"> Close </button> <button class="px-4 rounded-lg text-white transition ease-in-out delay-150 bg-blue-500 hover:-translate-y-1 hover:scale-110 hover:bg-indigo-500 duration-300"> Authorize </button> </div> </div> </form> `; modal.classList.remove('hidden'); } This modal works successfully. The only problem is that when this {% csrf_token %} is not actually embedded into the page but it's rendering as a string. I know as I'm adding this piece of HTML after the page is already rendered by the Django. That's why this is happening. Is there any way that I can get this working? -
Getting data for multiple objects using django checkbox
I want to get data of all objects that are selected in django admin panel using the checkbox but i can't get it right: class SalesView(View): def get(self, request, sales): sales = SaleItem.objects.all() i know i need to turn this all() function to filter to get id but just won't work! -
refar a path in root of django project from a tamplate
I have this structure: Project common Application templates common index.html static ... app1 Application ... app2 Application ... ... node_modules swiper swiper-bundle.min.css I have write this code in index.html: <link rel="stylesheet" href="../../../node_modules/swiper/swiper-bundle.min.css"> But not working and the swiper-bundle.min.css file not found. So, if I use this path href="/static/swiper-bundle.min.css" and the swiper-bundle.min.css stores in root/common/static it will works truely. How can access the swiper-bundle.min.css has located in root/node_modules/swiper/swiper-bundle.min.css ? -
String comparision returning False even if they are the same in python , inside a html file in DJANGO
so there is this IF statement inside a html file , which is failing to return a TRUE when both the strings are the same , i dont know why , i copy pasted the same strings from database to another python compiler and it said TRUE but it is only failing here I will add a sscreenshot of a reverse case where i will print it if they are not equal so you can see the string and confirm enter image description here this is the printed ones , i currently have 2 comments in my database enter image description here here it prints for both case ,hence shows how both strings are not same for both cases im using django one of the fields is a CharField with max length of 500 and another (post_id = models.CharField(max_length=500)) another is a uuid field (id = models.UUIDField(primary_key=True, default=uuid.uuid4)) i tried is instead of == , still fails im expecting it to only return a TRUE if both strings are equal ( please ignore the != in screenshot as it is just to print out the strings) -
How to annotate django queryest using subquery where that subquery returns list of ids from related model records
I have one database model, let's say ModelA: class ModelA(models.Model): field_1 = models.ManyToManyField( "core.ModelB", blank=True ) user = models.ForeignKey("core.User", on_delete=models.CASCADE) type = models.CharField(choices=ModelATypes.choices) The field_1 of ModelA is a many to many field that references ModelB. class ModelB(models.Model): uid = models.UUIDField(unique=True, default=uuid.uuid4, editable=False) amount = models.IntegerField() Now, I want to annotate the queryset to show the list of uid's from field_1 based on some filter like get the list of ModelB uid's from field_1 where user in ModelA is in list of applicable user ids. Example: from django.db.models import Subquery user_ids = [1, 2, 3] result = ModelA.objects.filter(type="year").annotate( model_b_uids_list=Subquery( ModelA.objects.filter(user__id__in=user_ids).values_list("field_1__uid", flat=True) ) ) This gives error more than one row returned by a subquery used as an expression. I tried using ArrayAgg function but that does not seems to be working. I want the annotated field model_b_uids_list on ModelA to have a list of uid's from the field_1 from multiple applicable records on ModelA. Can anyone help me understand what's going wrong here? -
I get an error when making a blog project
Hello, I'm trying to make a blog site with django but I'm getting an error, the error is NoReverseMatch at / Reverse for 'blog_detail' with keyword arguments '{'slug': ''}' not found. 1 pattern(s) tried: ['blog\-detail/(?P[-a-zA-Z0-9_]+)\Z'] I tried different methods but it didn't work, can anyone help me? someone who can look at my project in detail? I have tried many different methods but could not resolve the error. -
Django JSON dumpdata bug
при дампе Json файлов кириллица отображается некорректно, подскажите что делать Json python manage.py dumpdata products.productCategory > categories.Json при работе с джанго для того что бы не восстанавливать все данные в SQLite3 вручную решил сделать дамп но кириллица в Json файлах отображается некорректно Json -
Ordering by the column which is connected with foreign key
I have classes like this, Drawing has the one CustomUser class CustomUser(AbstractUser): detail = models.JSONField(default=dict,null=True,blank=True) NAM = models.CharField(max_length=1024,null=True,blank=True,) class Drawing(SafeDeleteModel): detail = models.JSONField(default=dict,null=True, blank=True) update_user = models.ForeignKey(CustomUser,on_delete=models.CASCADE,related_name='update_user') Now I wan to get the list of Drawing by sorting Drawing.update_user.NAM then i made code like this, class DrawingViewSet(viewsets.ModelViewSet): queryset = m.Drawing.objects.all() serializer_class = s.DrawingSerializer pagination_class = DrawingResultsSetPagination filter_backends = [filters.OrderingFilter] ordering_fields = ['id','update_user.NAM'] ordering = ['-id'] then call with this url http://localhost/api/drawings/?ordering=-update_user.NAM http://localhost/api/drawings/?ordering=update_user.NAM However in vain. How can I call this ordering? -
React django file upload difference in content-length
I'm trying to upload a PDF file from my react client to my django server (both running locally on my laptop), but I'm observing a difference in the size of the file that is sent from my react client and the file received in the request receieved at my server. The file received in the request at the server does not seem to be a valid PDF file either. This seems to be happening for other file types as well. Attaching relevant screenshots and snippets below where I'm trying to upload a PDF file which is ~4.5 MB in size: React client snippet for uploading the file: const formData = new FormData(); formData.append('file', acceptedFiles[0]); // acceptedFiles comes from a form input const uploadFilesResponse = await axios.request({ method: 'POST', url: `/api/documents/upload/${pathToUpload}`, data: formData, headers: { 'Content-Type': 'multipart/form-data', }, }); The network tab indicating the request I've sent and the file in the request payload: Here's the corresponding request received at the server Even the on disk temporary file created by django for the upload highlighted above (/var/folders/tf/7xrq4m4j11dcfkngpz9j3rfm0000gn/T/tmpil4f5hsn.upload.pdf) seems to be an invalid file which is ~8.5 MB in size. The request object shared above is the request object received at my … -
How can I use only my custom models with social-auth-app-django?
How can I store people logged in or registered with social authentication only in the custom user model? By default, whenever I use social auths, they are registered in User social auths in PYTHON SOCIAL AUTH on the Admin page, but I would like to remove this duplication with the custom user model. This does not mean that I want those displays to disappear from the admin page, but rather that I want to optimize the database space. Libraries I use are DRF, socil-auth-django and Djoser. I want to keep only my custom user model. No other user model is needed. -
Is it possible to remove an item type from a lineitem.aggregate when making a different calculation?
The delivery cost should not include % on booking, but should include % of product price if below the set delivery threshold. Both can be added to an order and at checkout only the product should attract a delivery cost, as the booking relates to buying experiences. I am unable to figure this out, so if anyone can help me I would be most grateful. Below is my model code for checkout, which includes the Order Model where the delivery is being calculated, and Order Line Item Model from where the order total is being calculated using line item aggregate. def update_total(self): """ Updates grand total each time a line item is added, takes into account delivery costs """ self.order_total = self.lineitems.aggregate( Sum('lineitem_total'))['lineitem_total__sum'] or 0 if self.order_total < settings.FREE_DELIVERY_THRESHOLD: self.delivery_cost = self.order_total * \ settings.STANDARD_DELIVERY_PERCENTAGE / 100 else: self.delivery_cost = 0 self.grand_total = self.order_total + self.delivery_cost self.save() class OrderLineItem(models.Model): order = models.ForeignKey( Order, null=False, blank=False, on_delete=models.CASCADE, related_name='lineitems') product = models.ForeignKey(Product, null=True, blank=True, on_delete=models.CASCADE) experience = models.ForeignKey(Experiences, null=True, blank=True, on_delete=models.CASCADE) quantity = models.IntegerField(null=False, blank=False, default=0) lineitem_total = models.DecimalField( max_digits=6, decimal_places=2, null=False, blank=False, editable=False ) price = models.DecimalField( max_digits=6, decimal_places=2, null=False, blank=False,) def get_price(self, *args, **kwargs): if self.product and self.experience: return self.product.price … -
Manager's annotations don't show up when traversing ForeignKey
Suppose I have such classes: class UserManager(Manager): def get_queryset(self): return super().get_queryset().annotate( full_name=Concat( F('first_name'), Value(' '), F('last_name'), output_field=CharField() ) ) class User(Model): first_name = CharField(max_length=16) last_name = CharField(max_length=16) objects = UserManager() class Profile(Model): user = ForeignKey(User, CASCADE, related_name='profiles') And I want to include an annotated field in my query: Profile.objects.filter(GreaterThan(F('user__full_name'), Value(24))) But I got a FieldError: Cannot resolve keyword 'full_name' into field. Choices are: first_name, id, last_name, profiles It's clear that I could repeat my annotation in a current query: Profile.objects.filter(GreaterThan(Concat(F("user__first_name"), Value(" "), F("user__last_name"), output_field=CharField(),), Value(24))) But as soon as my annotations will become more complex, my code become mess. Is there any workaround? -
Cookies not being set in browser when making API request from React, but work with Django REST framework
When I use the Django REST framework to send a POST request to the login endpoint, the cookies are added to the response, and I can observe them in the browser. Additionally, I can confirm that I'm receiving the correct data (user ID and password) in both cases. However, when I use my React application to send the same POST request to the login endpoint, the cookies are not being added to the response, and consequently, they aren't stored in the browser. Again, I receive the correct data (user ID and password) in this scenario as well. My django rest code : @api_view(['POST']) def loginUser(request): print("request", request.data) id_Patient = int(request.data.get('id_Patient')) print("id_Patient", id_Patient) password = request.data.get('password') print("password", password) user = Patient.objects.filter(id_Patient=id_Patient).first() if user is None: print("user is None") return JsonResponse({"message": "User not found"}, status=404) if not user.check_password(password): print("not user.check_password(password)") return JsonResponse({"message": "Incorrect password"}, status=400) payload = { 'id_Patient': user.id_Patient, 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=60), 'iat': datetime.datetime.utcnow() } secret_key = os.urandom(32).hex() token = jwt.encode(payload, secret_key, algorithm='HS256') response = JsonResponse({"token": token}) response.set_cookie('my_cookie', 'my_value', httponly=True) # Set the cookie return response What Actually Resulted: Surprisingly, the cookies are being set correctly when I test the API request using Django's REST framework, and I'm receiving the … -
How to resolve ImproperlyConfigured: Cannot import 'core'. Check that 'OutilSuivisEffectifs.apps.core.apps.CoreConfig.name' is correct
my work flow: OutilSuivisEffectifs apps core migrations static templates __init__.py admin.py apps.py forms.py models.py tests.py urls.py views.py __initi__.py settings.py urls.py wsgi.py manage.py my Installed apps in OutilSuivisEffectifs/settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crispy_forms', 'django_countries', 'bootstrap3_datetime', 'captcha', 'OutilSuivisEffectifs.apps.core', 'import_export' ] my OutilSuivisEffectifs/apps/core/apps.py: from django.apps import AppConfig class CoreConfig(AppConfig): name = 'core' the command I am running is Python manage.py makemigrations The error I get execute_from_command_line(sys.argv) File "C:\Users\c69961\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\c69961\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 395, in execute django.setup() File "C:\Users\c69961\Anaconda3\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\c69961\Anaconda3\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\c69961\Anaconda3\lib\site-packages\django\apps\config.py", line 246, in create raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Cannot import 'core'. Check that 'OutilSuivisEffectifs.apps.core.apps.CoreConfig.name' is correct.` I tried to change name : from django.apps import AppConfig class CoreConfig(AppConfig): name = 'OutilSuivisEffectifs.apps.core' But same error -
Return HTTP 404 response with no content-type?
Is there a way in Django to return a HTTP 404 response without a content-type? I tried return HttpResponseNotFound() from my view, but that sends a Content-Type: text/html; charset=utf-8 header.