Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Httprequest has no attribute '_read_started'
I am trying to build a unittest for my weebhook_get_event(request). I use Django Httprequest to custom a request. When I test my function it said AttributeError: 'HttpRequest' object has no attribute '_read_started' on the line request.body def webhook_get_event(request): """ Exract the event form the request """ pdb.set_trace() event = None try: body = request.body.decode("utf-8") event = telnyx.Event.construct_from(body, telnyx.api_key) except: logger.exception(make_log_msg("get event failed", "", traceback.format_stack())) return evnet and my test is : class WebhookTest(TestCase): request = HttpRequest() def setUP(self): self.request.header = { 'telnyx-signature-ed25519' : "WkBFVhtpNBf+sOJ0+0sR1TntMqXsG2085AC1gvvRouPbHHlWZuDa7ZrHOFObucMOkcq3FY2/g9QzfD2EJ7FPAw==", 'telnyx-timestamp':"1615512013"} body = b'{"data":{"event_type":"message.received","id":"bc8ffc8d-89f6-4ee9-b28e-d15ea5a644da","occurred_at":"2021-03-12T01:20:13.341+00:00","payload":{"cc":[],"completed_at":null,"cost":null,"direction":"inbound","encoding":"GSM-7","errors":[],"from":{"carrier":"","line_type":"Wireless","phone_number":"+13125047267"},"id":"e3b8d304-c0d9-44a8-a6c0-73bb1d2665e9","media":[],"messaging_profile_id":"400177e5-e558-42c2-af2a-6b33574c2088","organization_id":"9da44375-48a0-46d2-9215-f788493def7c","parts":1,"received_at":"2021-03-12T01:20:13.335+00:00","record_type":"message","sent_at":null,"tags":[],"text":"hello","to":[{"carrier":"Telnyx","line_type":"Wireless","phone_number":"+155555555","status":"webhook_delivered"}],"type":"SMS","valid_until":null,"webhook_failover_url":null,"webhook_url":"https://encf7aq9g1rclj9.m.pipedream.net"},"record_type":"event"},"meta":{"attempt":1,"delivered_to":"https://encf7aq9g1rclj9.m.pipedream.net"}}' self.request._body = body def test_webhook_get_event(self): event = webhook.webhook_get_event(self.request) assertNotNone(event) -
calculate remaining days in python/django
I'm creating a django ecommerce site; This site "sells" digital items. On one of the templates, related to a "user profile", I'm trying to calculate the remaining days in an web app but so far have not been successfull at doing it and displaying on my template. I've tried to create a remaining_days function but unable so far to use it Hereunder the code: models.py class UserSubscription(models.Model): user = models.ForeignKey(User, related_name= 'tosubscriptions', on_delete=models.CASCADE, null=True, blank=True) subscription = models.ForeignKey("Subscription", related_name = 'tosubscriptions',on_delete=models.CASCADE, null=True, blank=True) # startdate of a subscription, auto_now_add needs to be "False" for acummulation of days in subscriptions start_date = models.DateTimeField(auto_now_add=False, null=True, blank=True,verbose_name="Start Date") expiry_date = models.DateTimeField(auto_now=False, auto_now_add=False, null=True, blank=True,verbose_name="Expiry Date") # expiry date of a subscription # "is_canceled" is used to calculate if a usersubscription is active is_canceled = models.BooleanField(default=False, verbose_name="Is Canceled") cancel_date = models.DateTimeField(auto_now=False, auto_now_add=False, blank=True, null=True) class Meta: verbose_name = "User Subscription" verbose_name_plural = "User Subscriptions" def __str__(self): """Unicode representation of UserSubscription""" return "PK: [{}] Subscription of: {}, {}, Expiring the: {}, is canceled: {}".format( str(self.pk), str(self.user), str(self.subscription), str(self.expiry_date), str(self.is_canceled ) ) def save(self, *args, **kwargs): # calculated when object is saved and saved in the db """ Function to calculate the expiry date of a … -
Annotating values from filtered related objects -- Case, Subquery, or another method?
I have some models in Django: # models.py, simplified here class Category(models.Model): """The category an inventory item belongs to. Examples: car, truck, airplane""" name = models.CharField(max_length=255) class UserInterestCategory(models.Model): """ How interested is a user in a given category. `interest` can be set by any method, maybe a neural network or something like that """ user = models.ForeignKey(User, on_delete=models.CASCADE) # user is the stock Django user category = models.ForeignKey(Category, on_delete=models.CASCADE) interest = models.PositiveIntegerField(default=0, validators=[MinValueValidator(0)]) class Item(models.Model): """This is a product that we have in stock, which we are trying to get a User to buy""" model_number = models.CharField(max_length=40, default="New inventory item") product_category = models.ForeignKey(Category, null=True, blank=True, on_delete=models.SET_NULL, verbose_name="Category") I have a list view showing items, and I'm trying to sort by user_interest_category for the currently logged in user. I have tried a couple different querysets and I'm not thrilled with them: primary_queryset = Item.objects.all() # this one works, and it's fast, but only finds items the users ALREADY has an interest in -- primary_queryset = primary_queryset.filter(product_category__userinterestcategory__user=self.request.user).annotate( recommended = F('product_category__userinterestcategory__interest') ) # this one works great but the baby jesus weeps at its slowness # probably because we are iterating through every user, item, and userinterestcategory in the db primary_queryset = primary_queryset.annotate( … -
OpenCV Live Stream from Camera in Django webpage with image details
I am making a project in Django. And have made live feed from camera on a webpage. I am also processing the video to detect faces, and gestures. But I am not able to send the array (i.e which contains the features of videos like face detected or not, hand gesture, etc) to the template. Views.py: from django.shortcuts import render from django.http.response import StreamingHttpResponse from streamapp.camera import VideoCamera from django.http import HttpResponse def gen(camera): while True: frame = camera.get_frame() feature = camera.render_features() print(feature) yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') def video_feed(request): return StreamingHttpResponse(gen(VideoCamera()), content_type='multipart/x-mixed-replace; boundary=frame') def index(request): return render(request, 'streamapp/home.html') Urls.py: from django.urls import path, include from streamapp import views urlpatterns = [ path('', views.index, name='index'), path('video_feed/', views.video_feed, name='video_feed'), ] In View.py line number 10, feature is the array that I want to access inside the webpage(home.html). How to pass that array to the template? -
@permission_required doesn't check user group permissions
I am trying to check if a user has a permission to access a particular django view using @permission_required. The permission is assigned to the group x to which the user is assigned to. I confirmed with the database and through debugging that the user is member of the group and the group has the appropriate permission set. Nevertheless, @permission_required doesn't allow access to this user. The view has the following decorators: @login_required(login_url='ROUTE') @permission_required('PERMISSION', raise_exception=True) Is this an issue from django, or is there some workaround that needs to be done to consider group permissions? -
Creating automated docs for Django REST Framework
guys. I am to write documentation for Django (specially docs for APIs) project and want to use Sphinx. Unfortunately, Sphinx` docs and guides are out of date (Sphinx newest version is 3.5+). When I mean out of date guides and docs, I refer to this guides and others: https://www.freecodecamp.org/news/sphinx-for-django-documentation-2454e924b3bc/ (2018) https://www.sphinx-doc.org/en/master/usage/quickstart.html (official docs, it doesn't help) https://docs.djangoproject.com/en/dev/internals/contributing/writing-documentation/ https://columbia-it-django-jsonapi-training.readthedocs.io/en/latest/sphinx/ (Sphinx 1.8) The problem is that there are docs directory, that doesn't appear in new versions (in newest versions we`ve got sourse directory). I installed Sphinx to test project and run command sphinx-quickstart in app directory. My structure in test project after sphinx-quickstart: Test -- app ---- base ---- **build** ---- post ---- quickstart ---- templates ---- **sourse** ------ **_static** ------ **_templates** ------ **conf.py** ------ **index.rst** ---- **make.bat** ---- **Makefile** ---- manage.py ---- requirements.txt -- venv -- .gitignore -- Dockerfile -- docker-compose.yaml -- README.md Files between **** is what I`ve got after running sphinx-quickstart. If you know how to work with new version of Sphinx or now other services for automate generating docs for DRF and API, please, explain or provide link to actual docs of Sphinx -
how to extract specific values from json / dictionary in Python (Django)
This is my views.py : import requests import os import numpy as np import pandas as pd from pandas import Series, DataFrame from pprint import pprint from django.views.generic import TemplateView import json from django.http import JsonResponse, HttpResponse from django.shortcuts import render def btc(request): query_url = [ 'https://api.blockchair.com/bitcoin/stats', 'https://api.blockchair.com/ethereum/stats', 'https://api.blockchair.com/litecoin/stats' ] headers = { } result = list(requests.get(u, headers=headers) for u in query_url) json_data1 = result[0].json() json_data2 = result[1].json() json_data3 = result[2].json() y = json_data1['data']['transactions'] context = { "bitcoin": y, "ethereum": json_data2, "litecoin": json_data3, } return render(request, "index.html", context) the problem is in the variable : 'y' in the index.html file : ethereum.data.transaction for example works perfectly so i want to do the same thing but directly into the views.py file (in python) because i need the variable to be a simple value not a json/dict value -
How to render formset manually?
I can't figure out how to render formset manually. I created formset like this: ImageFormset = modelformset_factory(PostImages, fields=('image',), extra=0, can_delete=True). And when I render formset I get this: I want to get rid of all this text and write my own, how do I do this? -
Django, Dash App Safest Place to Keep Database Credentials
I'm new to web development. I have a Django project that loads a Dash app on one of it's pages. The dash app generates a chart that lets the user select certain datasets from the database. Directly inside my App.py (dash app) I placed my sqlalchemy database connection variables which one of the callbacks uses to fetch the data when requested. sqlEngine = sa.create_engine('mysql+pymysql://host:password@127.0.0.1:3306/db', pool_recycle=3600) dbConnection = sqlEngine.connect() conn = pymysql.connect(host='127.0.0.1',user='host',password='password',db='db') cursor = conn.cursor() app = DjangoDash(name='app', add_bootstrap_links=True, serve_locally = False) ... @app.callback(...) def fetch_data(...): select = """SELECT * FROM `db`.`table`;""" df = pd.read_sql(select, dbConnection) I'm not sure if this is a safe practice in a production environment. What would be the best/safest way to connect to the database inside of the dash app. My Django app is also connected to the database for migrations. Thanks for any help/advice. -
Django Render List of Dictionaries to a template
I have a list of dictionaries with same key information. How can I pass this list of dictionaries to a Django template ? listdict = [{'product':'specs','price':'12'}, {'product':'shoes','price':'30'}] When trying to send this list via views file to template it fails with an error indicating that only dictionaries are allowed. Here is the code from views file return render(request, 'recordings/extensionrecording.html',listDict) Here is the html block- <tbody> {%for list in listDict%} {%for elements in list%} <tr> <td class="body-item fonts-style display-4">{{elements.product}}</td> <td class="body-item fonts-style display-4">{{elements.price}}</td> </tr> -
Best way to query Repeating Events With available seat
I have a recurring events application, each event can have multiple recurrence patterns (RFC5445), a date can be in different recurrence patterns so I have added an autofield integer to prioritize the most recently added recurrences, each recurrence pattern has a max seat capacity. So far so good the problem starts when I need to check all the dates that have seats available for the next 365 days: I would have to check each date against a recurrence rule/pattern and finding that date get the capacity associated with the recurrence. maybe an example pseudocode is better understood than my English. ex.: reseved = "info with the number of person by each date reserved" patters = { 0:["RRULE:FREQ=DAILY;", "max 10 person"], 1:["RRULE:FREQ=MONTLY;UNTIL=2021-10-10", "max 15 person"] 2:[RRULE:FREQ=DAILY;UNTIL=2021-06-15", "max 25 person"] } patterns_ordered = patters.order_by["index] date = "2021-01-01" last_date = "2021-01-01" + 365 days while date < laste_date: for rule in patterns_ordered: If date in rule and rule.capacity > number_reserved in date: save date in array with it's availibility. -
can't call a variable in html using django refference
i have a contact page in html that has input text with the name 'lname' and when pressing on submit button it should provoque a function called contact ( created in views.py ) def contact(request): if request.method == 'POST': first_name = request.POST['fname'] last_name = request.POST['lname'] date = request.POST['date'] email = request.POST['email'] treatment = request.POST['treatment'] note = request.POST['note'] return render(request, 'contact.html', {'last_name': last_name}) else: return render(request, 'contact.html', {}) ``` and i called the last_name in that html page (contact.html ) the page is reloaded but the last_name is not displayed ``` <h1> hello - {{ last_name }} </h1> ``` please help i am new to django thanks a lot -
AttributeError: 'list' object has no attribute 'appened' Django
I'm a little new to Django and I am practicing by following this tutorial I am trying to make my slugs be created automatically whenever I add a product of a category. I have followed the tutorial exactly and I have searched around but nothing seems to be pertaining to my exact problem. The site was working fine until I added the following code. To my models.py I added two codes. def get_absolute_url(self): return reverse("category_detail", kwargs={"slug": self.slug}) I also added: slug = models.SlugField(null = False, unique= True) Below is the complete file. from django.db import models from django.db.models.deletion import CASCADE from django.utils.safestring import mark_safe from ckeditor_uploader.fields import RichTextUploadingField from mptt.models import MPTTModel from mptt.fields import TreeForeignKey from django.urls import reverse # Create your models here. class Category(MPTTModel): STATUS = ( ('True', 'True'), ('False', 'False' ), ) parent = TreeForeignKey('self', blank =True, null=True, related_name="children", on_delete=models.CASCADE) title = models.CharField(max_length = 30) keywords = models.CharField(max_length=255) description = models.CharField(max_length=255) image = models.ImageField(blank = True, upload_to = 'uploads/images') status = models.CharField(max_length=10, choices=STATUS) slug = models.SlugField(null = False, unique= True) created_at = models.DateField(auto_now_add=True) deleted_at = models.DateField(auto_now=True) def __str__(self): return self.title class MPTTMeta: order_insertion_by = ['title'] def get_absolute_url(self): return reverse("category_detail", kwargs={"slug": self.slug}) def __str__(self): full_path = [self.title] … -
In djago if you extend the user model and you using profile model
Than how we use below code if we want mobile attribute from profile model ? user.profile.mobile but profile class has user reference it means it can be possible to access username like this profile.user.username -
Unable to import 'todo.models'pylint(import-error)
I am encountering error as below when I want to import the other app: enter image description here And, I have tried djangotodoapp.todo.models, .models, ..todo.models but they do not works. After that, you can check out my settings.py from below image. enter image description here How can I fix this problem? Thank you in advance. -
Django Rest Framework Model Serializer Aditional Keyword Argument not recognized
I have the following DRF serializer: class ServiceStatusSerializer(serializers.ModelSerializer): class Meta: model = models.ServiceStatus fields = ('id', 'service', 'status', 'timestamp', 'comment') extra_kwargs = {'content_object': {'write_only': True}} def create(self, validated_data): result = super().create(validated_data) return result I am trying to implement additional keyword arguments to ModelSerializers as described here, but serializer's create() method doesn't receive the extra parameter in validated_data, as you can see in this debug watch expression: You can see that validated_data parameter only contains three keys and misses key content_object, even when it was sent from Postam POST request: I can't find out what I am missing. -
Listen to events from apps like Slack and update Django database
I want to build a Django app which listens to events from messaging apps and writes them in a database. For eg, in Slack, on channel creation, I want to create a new entity in database and when a message is posted in that channel, I want to update that entity with the message. I want the app to work similarly for other apps like Telegram, Discord etc. How can I implement this using a common backend API for all the apps, i.e. a common API which listens to the events and updates the db ? Or is there some third-party API available (for eg. Twilio maybe) which can fulfil my purpose ? -
Django: ModuleNotFoundError after reinstalling Python and Django
I have two Django projects (project-x and project-y) which were running fine initially. However after reinstalling python and Django, I keep getting the error ModuleNotFoundError: No module named 'project-x' when I run python3 manage.py runserver for any of my other projects. This exact error occurs for every new project I create and try to run no matter its location. Everything was working before the reinstall and ready to ship so I am desperate to find out whats gone wrong .. Terminal chaudim@TD project-y % python3 manage.py runserver Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 61, in execute super().execute(*args, **options) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 68, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "/usr/local/lib/python3.9/site-packages/django/conf/__init__.py", line 82, in __getattr__ self._setup(name) File "/usr/local/lib/python3.9/site-packages/django/conf/__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "/usr/local/lib/python3.9/site-packages/django/conf/__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/local/Cellar/python@3.9/3.9.1_6/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 972, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1030, in _gcd_import … -
How to implement video conferencing with Django? [closed]
Can someone please guide me as to what all processes I need to follow in order to make a fully functional Video Conferencing App for my Django project (Virtual Classroom)? -
Django - Built in reset password links not working
I was following this tutorial on implementing the built in Django reset password views. I am using a custom User Model and I have read that when a user model inherits from AbstractUser, it should work with the password reset views as normal. However, none of them work. I am trying to access the reset form and nothing is displayed. Any help would be greatly appreciated Model class UserProfile(AbstractUser): contact_phone = models.CharField(max_length=100, unique=True) email = models.EmailField(unique=True) urls path('accounts/', include('django.contrib.auth.urls')), templates registration/password_reset_complete.html registration/password_reset_confirm.html registration/password_reset_done.html registration/password_reset_email.html registration/password_reset_form.html registration/password_reset_subject.txt Email backend for development EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' -
Passing login credentials to new view
The system uses django-tenant-schemas for separating data. The users are all on a shared schema so they can log in from any subdomain. To prevent them from seeing another companies data there is a middleware.TenantUserRedirectMiddleware which redirects the user to the proper subdomain after authentication. The problem is that it wants them to login once again after they get to the correct subdomain. I believe one solution is to get the login data from the request object and pass it to sessions then use that data to automatically authenticate the user at the subdomain so that they are not asked for credentials a second time. How do I get the login form data from request? I have tried this in the Middleware: class TenantUserRedirectMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if not request.user.is_superuser: if request.user.is_authenticated: if request.user.company != request.tenant: print(request.POST) # This is empty, where is the login data? if DEVELOPMENT: return HttpResponseRedirect( '//' + request.user.company.get_primary_domain().domain + ':8000/login/') return HttpResponseRedirect('//' + request.user.company.get_primary_domain().domain + '/login/') response = self.get_response(request) return response -
ValueError: Unable to configure handler 'file1' django with apache2 error
i am trying to run my django website with apache2 webserver on an ubuntu machine i configured everything almost as the django wsgi documentaion but when i try to open my website in the browser it dosen't work and it raises the following error ValueError: Unable to configure handler 'file1' i think the problem is related to the logging files i have in sittings.py itried to give the apache2 access to both of them but it didn't work sudo chown :www-data debug.log sudo chown :www-data info.log does any one know how i can fix this issue. here is my apache2 configuration file: <VirtualHost *:80> ServerAdmin admin@cryptobank.localhost ServerName cryptobank.localhost ServerAlias www.cryptobank.localhost DocumentRoot /home/hamzahfox/Desktop/CryptoBankApache ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/hamzahfox/Desktop/CryptoBankApache/static <Directory /home/user/django_project/static> Require all granted </Directory> Alias /static /home/hamzahfox/Desktop/CryptoBankApache/media <Directory /home/user/django_project/media> Require all granted </Directory> <Directory /home/hamzahfox/Desktop/CryptoBankApache/CryptoBank> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess cryptobank.localhost python-path=/home/hamzahfox/Desktop/CryptoBankApache python-home=/home/hamzahfox/Desktop/python/env/django-env WSGIProcessGroup cryptobank.localhost WSGIScriptAlias / /home/hamzahfox/Desktop/CryptoBankApache/CryptoBank/wsgi.py </VirtualHost> here is my wsgi.py file: """ WSGI config for CryptoBank project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'CryptoBank.settings') application = get_wsgi_application() here is my sittings.py … -
Django get_serializer 'NoneType' object is not callable
I am testing an API of Django (DRF) application. I am calling http://127.0.0.1:8000/api/users/1/documents/ (1 - user id) And receive an error ... File "/app/backend/apps/users/views/users/views.py" in create 542. serializer = self.get_serializer(data=request.data) File "/usr/local/lib/python3.7/site-packages/rest_framework/generics.py" in get_serializer 110. return serializer_class(*args, **kwargs) Exception Type: TypeError at /api/users/1/documents/ Exception Value: 'NoneType' object is not callable How can i identify the problem? Request related view /app/backend/apps/users/views/users/views.py (problematic line is serializer = self.get_serializer(data=request.data)) class UserDocumentCreate(generics.CreateAPIView, generics.RetrieveAPIView): serializer_class = UserDocumentSerializer permission_classes = (UserIsOwner, IsAuthenticatedDriver) queryset = Document.objects.all() def get_serializer_class(self): if self.request.version == "1.0": return UserDocumentSerializer # return UserDocumentSerializer2 def create(self, request, *args, **kwargs): request.data._mutable = True request.data["owner"] = kwargs.get("pk") serializer = self.get_serializer(data=request.data) if serializer.is_valid(raise_exception=True): owner = serializer.validated_data.get("owner") document_type = serializer.validated_data.get("document_type") message_status = request.data.get("message_status") documents = owner.document_owner.filter( document_type=document_type ) for document in documents: if document.status == DocumentStatus.DOCUMENT_REJECTED_STATUS: document.delete() # Mark user as new owner.is_new_user = True owner.save() self.perform_create(serializer) headers = self.get_success_headers(serializer.data) response = { "status": status.HTTP_201_CREATED, "result": serializer.data, } # accept corresponding registration message if message_status: driver_reg = DriverRegistration.objects.filter(user=kwargs.get("pk")).first() driver_reg.accept_by_status(message_status) next_id = driver_reg.get_next() # add information about next registration message to response if next_id != -1: response["next_message"] = REG_MESSAGES[next_id].to_json() return Response( response, status=status.HTTP_201_CREATED, headers=headers ) Related serializer (nothing special) class UserDocumentSerializer(serializers.ModelSerializer): is_new_document = serializers.BooleanField(read_only=True) class Meta: model = Document … -
super().__init__(*args, **kwargs) TypeError: __init__() got an unexpected keyword argument 'label'
Sir, my name is Karthik. I tried a multi-select-field project in Django. Based on my knowledge everything is correct. But, try to make migrations it shows TypeError. How to fix it. Please help me sir/madam. Error File "D:\My Django Projects\multiselectproject\multiselectapp\forms.py", line 4, in class EnquiryForm(forms.Form): File "D:\My Django Projects\multiselectproject\multiselectapp\forms.py", line 30, in EnquiryForm course = MultiSelectField(label='Select Required Courses:', choices='Courses_Choices') File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python39\lib\site-packages\multiselectfield\db\fields.py", line 70, in init super(MultiSelectField, self).init(*args, **kwargs) File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields_init_.py", line 986, in init super().init(*args, **kwargs) TypeError: init() got an unexpected keyword argument 'label' settings.py """ Django settings for multiselectproject project. Generated by 'django-admin startproject' using Django 3.1.2. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ import os 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.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'n&*#@g^b-%-$-yd1^!iwzhfnttd4s^zf+&$*5!i0_ves1v8s4&' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'multiselectapp.apps.MultiselectappConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', … -
Django 3.1: Choice of static files directory
I have seen different ways in tutorials where the static files directory keep on changing. 1. Some put static files in the project root directory. Example myproject |__blog | |__migrations | |__static | |__templates mysite | static |__blog |__css |__js 2. Some put the static files in the root directory of the app it is serving. Example myproject ├── blog │ ├── migrations │ ├── static │ └── templates └── mysite Where should static files be located?