Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest FrameWork: detail : "Authentication credentials were not provided."
I can fetch data but cannot post as I receive that error Heres what i have: https://github.com/ryan-howard-hc/Howti -
Unknown field(s) specified for a Page model in Wagtail at content_panels
Wagtail Django class AboutPage(Page): header_image = ImageChooserBlock() body = blocks.StreamBlock([ ('title', blocks.CharBlock()), ('content', blocks.RichTextBlock()), ]) content_panels = Page.content_panels + [ FieldPanel('header_image'), FieldPanel('body'), ] I keep getting this error, and I can't even begin to understand how to debug Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.10/threading.py", line 1016, in _bootstrap_inner self.run() File "/usr/lib/python3.10/threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "/home/khophi/Development/Photograph/venv/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/khophi/Development/Photograph/venv/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 133, in inner_run self.check(display_num_errors=True) File "/home/khophi/Development/Photograph/venv/lib/python3.10/site-packages/django/core/management/base.py", line 485, in check all_issues = checks.run_checks( File "/home/khophi/Development/Photograph/venv/lib/python3.10/site-packages/django/core/checks/registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/home/khophi/Development/Photograph/venv/lib/python3.10/site-packages/wagtail/admin/checks.py", line 70, in get_form_class_check if not issubclass(edit_handler.get_form_class(), WagtailAdminPageForm): File "/home/khophi/Development/Photograph/venv/lib/python3.10/site-packages/wagtail/admin/panels/base.py", line 134, in get_form_class return get_form_for_model( File "/home/khophi/Development/Photograph/venv/lib/python3.10/site-packages/wagtail/admin/panels/base.py", line 48, in get_form_for_model return metaclass(class_name, tuple(bases), form_class_attrs) File "/home/khophi/Development/Photograph/venv/lib/python3.10/site-packages/permissionedforms/forms.py", line 30, in __new__ new_class = super().__new__(mcs, name, bases, attrs) File "/home/khophi/Development/Photograph/venv/lib/python3.10/site-packages/modelcluster/forms.py", line 259, in __new__ new_class = super().__new__(cls, name, bases, attrs) File "/home/khophi/Development/Photograph/venv/lib/python3.10/site-packages/django/forms/models.py", line 321, in __new__ raise FieldError(message) django.core.exceptions.FieldError: Unknown field(s) (body, header_image) specified for AboutPage 9:43 Anyone with Wagtail Django experience should help -
How to count related objects
I am trying for a model to count related items and save that number into a interger field however it returns an error message: TypeError: default_order() missing 1 required positional argument: 'obj' Is there a better way to solve this problem and save the number of existing items related to a "level" field? Below is what I intend to be my code: def default_order(obj): n = Schedules.objects.filter(level=obj.level).count() return n class Schedules(models.Model): level = models.ForeignKey(Levels,related_name='levels',blank=False,null=False,on_delete=models.CASCADE) order = models.IntegerField(default=default_order) -
Django: Command to execute other commands?
I've created commands to create objects from my models. Can we have a command to execute them all? Or execute the all the commands in a folder, in a specific order? Example fo command: app/management/commands/products.py import pandas as pd import csv from shop.models import Product, Category from django.core.management.base import BaseCommand tmp_data_products = pd.read_csv('static/data/products.csv', sep=';', encoding='iso-8859-1').fillna(" ") class Command(BaseCommand): def handle(self, **options): products = [ Product( category=Category.objects.get(name=row['category']), name=row['product'], slug=row['slug'], sku=row['sku'], description=row['description'], available=row['available'], image=row['image'] ) for _, row in tmp_data_products.iterrows() ] Product.objects.bulk_create(products) -
im not able to migrate the files from my django app to AWS RDS
py manage.py makemigrations C:\Python311\Lib\site-packages\django\core\management\commands\makemigrations.py:143: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': connection to server at "database-1.cf9dt6lrnclf.eu-north-1.rds.amazonaws.com" (172.31.42.207), port 5432 failed: Connection timed out (0x0000274C/10060) Is the server running on that host and accepting TCP/IP connections? warnings.warn() py manage.py makemigrations C:\Python311\Lib\site-packages\django\core\management\commands\makemigrations.py:143: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': connection to server at "database-1.cf9dt6lrnclf.eu-north-1.rds.amazonaws.com" (172.31.42.207), port 5432 failed: Connection timed out (0x0000274C/10060) Is the server running on that host and accepting TCP/IP connections? warnings.warn() py manage.py makemigrations C:\Python311\Lib\site-packages\django\core\management\commands\makemigrations.py:143: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': connection to server at "database-1.cf9dt6lrnclf.eu-north-1.rds.amazonaws.com" (172.31.42.207), port 5432 failed: Connection timed out (0x0000274C/10060) Is the server running on that host and accepting TCP/IP connections? warnings.warn() py manage.py makemigrations C:\Python311\Lib\site-packages\django\core\management\commands\makemigrations.py:143: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': connection to server at "database-1.cf9dt6lrnclf.eu-north-1.rds.amazonaws.com" (172.31.42.207), port 5432 failed: Connection timed out (0x0000274C/10060) Is the server running on that host and accepting TCP/IP connections? warnings.warn() py manage.py makemigrations C:\Python311\Lib\site-packages\django\core\management\commands\makemigrations.py:143: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': connection to server at "database-1.cf9dt6lrnclf.eu-north-1.rds.amazonaws.com" (172.31.42.207), port 5432 failed: Connection … -
Loop through dictionary of lists django
Working on porting over a personal project of mine from flask to django, an issue I've been struggling with for a bit now is not being able to directly call index. Below is the code from my flask: {% for item in time_period %} <div class="col-lg-3 col-sm-4"> <div class="card h-100 border border-dark rounded"> <img class="card-image" src={{temp_icon[loop.index0]}}> </img> <div class="card-body"> <h2>{{item}}, {{temperature[loop.index0]}} F</h2> <p class="card-text">{{forecast[loop.index0]}}</p> </div> </div> </div> {% endfor %} In Django views, I have created this as. The weather.py module returns each variable as a list. def forecast(request): # Utilize weather.py to grab the forecast for the next three time periods as defined by NWS time_period, temperature, forecast, temp_icon = weather() context = {} context = {'time_period': time_period, 'temperature': temperature, 'forecast': forecast, 'temp_icon': temp_icon} print(context) return render(request, "forecast.html", context) sample data looks like 'time_period': ['This Afternoon', 'Tonight', 'Friday', 'Friday Night'], 'temperature': [88, 70, 95, 72], 'forecast': ['Partly Sunny', 'Slight Chance Showers And Thunderstorms', 'Chance Showers And Thunderstorms', 'Chance Showers And Thunderstorms'], 'temp_icon': ['https://api.weather.gov/icons/land/day/bkn?size=medium', 'https://api.weather.gov/icons/land/night/tsra_hi,20?size=medium', 'https://api.weather.gov/icons/land/day/rain_showers,20/tsra_hi,40?size=medium', 'https://api.weather.gov/icons/land/night/tsra_hi,30?size=medium'] Currently in my template I have been having a hard time looping through each list in parallel. My view shows the time_period piece correctly but unfortunately I have been unable to utilize the … -
Can Django be 100 times faster than Laravel?
Can Django be 100 times faster than Laravel (1 ms vs 100 ms) in performing REST CRUD operations? Same database, etc. Default settings as provided when starting the framework. Run on localhost, no docker. I tried turning off middleware and whatnot. -
django sqlmigrate stuck in a buggy migration
I have a small model for restaurants where I added an item_image attribute that receives url string. But instead of CharField I defined it as IntegerField . Then I ran python manage.py makemigrations food and python manage.py sqlmigrate food 0002 . I gave an error ValueError: Field 'item_image' expected a number but got 'https://cdn-icons-png.flaticon.com/512/1377/1377194.png'. I noticed the typo and fixed it( changed IntegerField to CharField). from django.db import models # Create your models here. class Item(models.Model): def __str__(self) -> str: return self.item_name item_name = models.CharField(max_length=200) item_desc = models.CharField(max_length=200) item_price = models.IntegerField() item_image = models.CharField(max_length=500, default='https://cdn-icons-png.flaticon.com/512/1377/1377194.png') but after I ran python manage.py sqlmigrate food 0002 the error is still there and when I change it to python manage.py sqlmigrate food 0003 and then run it. it gives no error but now for changes to take place I have to run python manage.py migrate which still gives the error on migration no.0002 How can I ignore this migration? -
could not be created because the data didn't validate
I'm trying to use a ModelForm to create and save an object to my database, but I keep getting a ValueError telling me my data isn't validated once I submit the POST data. when I fill date from form I get a error, "could not be created because the data didn't validate" This is in models.py class BookPublishedOrder(models.Model): author_name = models.CharField( max_length=100, verbose_name="Author Name") author_summary = models.TextField( max_length=100, verbose_name="Author summary") book_title = models.CharField( max_length=100, verbose_name="Book Title") book_subtitle = models.CharField( max_length=100, verbose_name="Book Sub Title", blank=True) book_category = models.CharField(max_length=100, verbose_name="Book Category", blank=True) book_summary = models.TextField( max_length=100, verbose_name="Book summary") book_picture = models.ImageField( upload_to='Book Published Order', verbose_name="Book Picture", blank=True) email_address = models.CharField( max_length=100, verbose_name="Email Address") phone_number = models.CharField( max_length=100, verbose_name="Phone Number") facebook_account = models.CharField( _("Facebook Account"), max_length=200, blank=True) instgram_account = models.CharField( _("Instgram Account"), max_length=200, blank=True) twitter_account = models.CharField( _("Twitter Account"), max_length=200, blank=True) book_PDF = models.FileField( upload_to="Book PDF", verbose_name="Book PDF") class Meta: verbose_name = 'كتاب مطلوب للنشر' verbose_name_plural = 'الكتب المطلوبة للنشر' This is in forms.py class BookPublishedOrderForm(forms.ModelForm): author_name = forms.CharField( max_length=100, label="إسم الكاتب") author_summary = forms.CharField(label="ملخص عن الكاتب") book_title = forms.CharField( max_length=100, label="عنوان الكتاب") book_subtitle = forms.CharField( max_length=100, label="عنوان الفرعي للكتاب", required=False) book_category = forms.CharField( max_length=100, label="نوع الكتاب", help_text="100 characters max.", required=False) book_summary = … -
Which app to put Django URL/view for add to cart functionality?
I am building a storefront application with Django. I have two apps, inventory and cart. I am implementing the functionality to add an InventoryItem to the cart, where it becomes a CartItem. Do I put the AddToCartView in the inventory app or the cart app? In the inventory app, I could have a URL like /inventory/<int:pk>/addToCart/, and in the cart app I could do something like /cart/<int:inventory_item_pk>/new/. Which of these is more RESTful? -
Django AdminDocs with Uppercase App Names
I am trying to implement Django's Admin Docs (django.contrib.admindocs) into my project. I've now realized that the best practice for app names is to be lower case, as the generated urls default to a lowercase url name. For example, my app name is Projects: Stores all Project entries, related to :model:`Projects.Project` On the admin page, the generated url leads to admin/doc/models/projects.project/ instead of admin/doc/models/Projects.project/ Is there an easy way to resolve this without having to rename every app in my project? When manually changing the url to the app name (uppercase), the page works as intended. -
Getting error while writing the dynamic URL in Django
I am trying to build a webapp using Django and in that I wanna add the delete functionality but when I put the id the URL in the template, it gives an error saying Reverse for 'remove_items' with arguments '('',)' not found. 2 pattern(s) tried: ['remove_items/(?P<rem_id>[0-9]+)/\\Z', 'remove_items/\\Z'] Below is the view. def dashboard_home(request): password_items = PasswordItem.objects.all() space = Space.objects.all() context = {'space':space, 'password_items':password_items} return render(request, 'dashboard_home.html', context) def remove_items(request, rem_id): passitem = PasswordItem.objects.get(pk=rem_id) passitem.delete() return redirect('dashboard_home') Below is the link for delete from the template. <a class="dropdown-item remove-item-btn" href="{% url 'remove_items' password_items.id %}"> <i class="ri-delete-bin-fill align-bottom me-2 text-muted"></i> Delete </a> Below is the url that I am using. path('remove_items/<int:rem_id>/', views.remove_items, name='remove_items'), I don't know why I am getting this error. It seems all good to me. -
Who can explain me how to make login by token without password using rest framework django and simple-jwt?
I have simple problem and can't solve it. I have sigle page site looks something like that <div id="login"></div> <div id="leaderboard_win" style="display: none;"></div> <div id="before_start"></div> <div id="game"></div> <div id="rules_text" class="bg-info"></div> When you go to the site i want to check token. var token = localStorage.getItem("my_game_token"); $.ajax({ url: "http://127.0.0.1:8000/api/v1/verify_player/", type: "POST", headers: { "Authorization": "Bearer " + token } }).done(function(data) { console.log(data) }).fail(function(xhr) { if (xhr.status === 401) { $('#login').show() $('#leaderboard_win').remove() $('#before_start').remove() $('#game').remove() } }) If the token exists then return the player's name and best time and remove #login accordingly and show before start. If the token does not exist or wrong then as shown above. And wait until the user enters data. $.ajax({ url: "http://127.0.0.1:8000/api/ego/verify_player/", type: "POST", data: { name : $("#player_name").val(), phone_number : $("#player_phone").val(), }, }).done(function(data) { console.log(data) // window.location.reload() }) if name and phone number exists in db give new token and save in local storage and return the player's name and best time and remove #login accordingly and show before start. if not exists create new player and return token. what i have now. managers.py from django.contrib.auth.models import UserManager as DefaultUserManager class UserManager(DefaultUserManager): def create_user(self, phone_number, name, password=None, **extra_fields): if not phone_number: raise ValueError('The Phone Number … -
How Do I Pass HIdden HTML Value From One Page To Another?
I know there are many variations of answers here but none that seem to fit my use case. I'm using Django.....I am trying to pass a page number from one page to another when I click on an tag. I have defined the hidden input on both HTML pages...but can't seem to figure out how to get the value.... Here's my View... def get_context_data(self, **kwargs): context = super(ListView, self).get_context_data(**kwargs) page_number = self.request.GET.get('page') context['page_number'] = page_number return context Here's my HTML... First HTML Page <form method="POST" id="forms"> <table> <td><a href="{% url 'Main:notify_update' pk=notify.id %}">{{ notify.new_vacation_calendar.status }}</a></td> <input type="hidden" id="page_number" value="{{ page_number }}"> </table> </form> The above renders correctly.... My second page.... <form method="POST"> <button type="button" class="button67">Button</button> <input type="hidden" id="page_number"> </form> My Javascript... $(document).ready(function (){ $('.button67').on('click', function (event) { var page = document.getElementById("page_number").value; console.log(page); }); When I try to process the second page....the value isn't being passed and I can't figure out what I'm missing. I'm used to passing values via the URL...but can't seem to figure out how to do this without using the URL. Thanks in advance for any tips on what I'm doing incorrectly. -
How to check if static files are loaded with prodcution environment?
I have dockerized a django app. And "everything" seems to work. The docker containers are up and running. And I can access the django admin url. But I try to figure out how to check if the static files will be loaded if I will deploy it on the azure environment. Because at the moment I am testing the production environment still on localhost. And even when I am setting the debug to 1. The static files are not loading. So this is the docker compose file: version: "3.9" services: web: build: context: ./ dockerfile: Dockerfile.prod restart: always command: gunicorn Welzijn.wsgi:application --bind 0.0.0.0:8000 volumes: - static_volume:/web/staticfiles - media_volume:/web/media expose: - 8000 environment: - DEBUG=1 env_file: - ./.env.prod proxy: build: ./proxy restart: always depends_on: - web ports: - 1337:80 volumes: - static_volume:/web/staticfiles - media_volume:/web/media volumes: static_volume: media_volume: And part of settings.py file: SECRET_KEY = os.environ.get('SECRET_KEY') DEBUG = os.environ.get('DEBUG') == "1" ALLOWED_HOSTS = ['*'] ALLOWED_HOSTS.extend( filter( None, os.environ.get('ALLOWED_HOSTS', '').split(" "), ) ) CSRF_TRUSTED_ORIGINS = ["http://localhost:1337"] STATIC_URL = '/static/' MEDIA_URL = '/media/' STATIC_DIRS = [ (BASE_DIR, 'static') ] STATICFILES_DIRS =[BASE_DIR / 'static'] STATIC_ROOT = BASE_DIR /'staticfiles/' MEDIA_ROOT = BASE_DIR /'media' and in the env.prod I also setted DEBUG=1 And I am using the … -
Django Channels not receiving the event raised from library
This is my Consumer Class. from channels.generic.websocket import WebsocketConsumer,AsyncWebsocketConsumer from channels.layers import get_channel_layer import asyncio import random import json class TradeSession(AsyncWebsocketConsumer): async def connect(self): print("In Consumer Now") self.room_name = "test_consumer" self.room_group_name = "test_consumer_group" await self.channel_layer.group_add(self.room_name, self.channel_name) await self.accept() async def disconnect(self, close_code): print("Disconnected Now") await self.channel_layer.group_discard(self.room_group_name, self.channel_name) raise channels.exceptions.StopConsumer() async def receive(self, text_data=None, bytes_data=None): print("Data Recieverd") pass async def send_number(self, event): print("in Send number Send event",event) number = event["price"] print("Actuly sending now ",number) await self.send(text_data=json.dumps({"price": number})) Following Is my Communicator liberary from where I am trying to raise an event. from channels.layers import get_channel_layer from asgiref.sync import async_to_sync import asyncio class Communicator: def __init__(self): pass def send_data_to_channel_layer(self, data, group_name): group_name = "test_consumer_group" print("In liberary sending data") channel_layer = get_channel_layer() print("Sendiong now to group",group_name) async_to_sync(channel_layer.send)(group_name, { "type": "send.number", "price": data['price'], }) # print("Message sent to group") In the logs I can see till the point - Sendiong now to group",group_name And after this log I see nothing on the console To add to to this My websocket is working fine And i have verified that from the client as well I am using redis-channel for the internal communication for channals This is the configuration for the same CHANNEL_LAYERS = { "default": … -
Django migrate uses wrong database backend for some migrations
Summary Consider a project with two local database configurations, called 'sqlite' (default) and 'postgresql'. Running migrate --database=postgresql successfully migrates the first few migrations to postgresql, then, suddenly, starts using the wrong database backend, resulting in the following error: sqlite3.OperationalError: no such table: myapp_mymodel Background Working on a legacy Django 3.2 project with over ten apps and over two-hundred migrations in total. The project is configured to use PostgreSQL in production, but uses SQLite for local testing. Now, for consistency, I want to configure the project to use PostgreSQL locally as well, instead of SQLite. So, here's what I did: created a brand new PostgreSQL database on the local dev system, configured for Django added a database configuration called 'postgresql' to the local settings file, in addition to the 'default' SQLite configuration (see example below) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', ..., }, 'postgresql': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', ..., }, } tested and verified the database and corresponding Django configuration ran python manage.py migrate --database=postgresql That's where things went wrong. Problem The first hundred migrations (approx.) were applied properly, but then Django ran into an error: Running migrations: Applying myapp.0002_copy_data_from_mymodel...python-BaseException Traceback (most recent call last): ... sqlite3.OperationalError: no such table: myapp_mymodel … -
django.utils.formats.date_format returning messy result
In Django 1.11, given a datetime.datetime object, e.g. datetime.datetime(2023, 8, 24, 16, 50, 5, 685162, tzinfo=<DstTzInfo 'Europe/Bucharest' EEST+3:00:00 DST>) I am trying to format it to 24.08.2023 by invoking: from django.utils.formats import date_format date_format(date, 'NUMERICAL_DATE_FORMAT') Instead of the expected result, I get: Aug.1692885005AugAugustR1CPMFalse_ThuPMEESTAugust_August+0300RAugPMEEST As per the Django docs, I've defined NUMERICAL_DATE_FORMAT = 'd.m.Y' in my FORMAT_MODULE_PATH. What am I missing? -
Reset password for user who registered with Social Auth (Google) [Django, Djoser, Social Auth]
I am trying to using custom model with Djoser JWT endpoint but I want to reset the password for those user who register with Google OAuth. When I am using the API endpoint the password reset mail is not getting send to mail. Any suggestion is appreciated. I tried to alter the reset password to get the email ID but i am not able to fetch the Email ID from custom user model. -
problem with internal files in django command line
I started learning django and ran into a problem I wanted to add products via the command line, but ran into a problem: Traceback (most recent call last): File "C:\Program Files\JetBrains\PyCharm 2023.2\plugins\python\helpers\pydev\pydevconsole.py", line 364, in runcode coro = func() File "", line 6, in File "C:\Users\dratyti\OneDrive\Рабочий стол\store-server\venv\lib\site-packages\django_init_.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "C:\Users\dratyti\OneDrive\Рабочий стол\store-server\venv\lib\site-packages\django\conf_init_.py", line 82, in getattr self.setup(name) File "C:\Users\dratyti\OneDrive\Рабочий стол\store-server\venv\lib\site-packages\django\conf_init.py", line 63, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I tried to find information on the internet, but I didn't find anything -
django-jsignature on a modal not showing until I change the screen size
I'm trying to get a Django-signature form into a modal but the pad were to sign isn't loading. The modal and the rest of the form, buttons and whatnot are there and fine. If I then change the size screen, either changing the actual size of the browser or by entering responsive design mode/toggle device toolbar on web developer tools, the pad will appear and work fine. Its probably a size/resize issue with the library but I seem to get stuck here. PS. all is fine if don't use modal but a full html page instead. The code: test.html : (loading the modal with a btn call to htmx) <button type="button" class="btn btn-primary" hx-get="{% url 'tools:test_signature' %}" hx-target="#modal-fullscreen-signature-content" hx-trigger="click"> Launch signature </button> view.py : (not checking for post or anything, its juts a test to make the signature work) def test_signature(request): signform = forms.SignatureForm() context = {'signform': signform,} return render(request, 'tools/test_signature.html', context) forms.py: from jsignature.widgets import JSignatureWidget class SignatureForm(forms.ModelForm): class Meta: model = Signature fields = "__all__" modal: <div class="modal fade" id="modal-fullscreen-signature" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true"> <div class="modal-dialog modal-fullscreen"> <div class="modal-content"> <div class="modal-body" id="modal-fullscreen-signature-content"> </div> <div class="modal-footer"> <button id="save_btn" hx-post="{% url 'tools:test_signature' %}" type="button" class="btn btn-secondary" data-bs-dismiss="modal">Save</button> <button type="button" … -
My app named store does not get recognized to migrate
When migrating, my app 'store' seems to not be recognized. It is already installed inside setting.py but still states "No installed app with label 'store'"enter image description here When migrating the _0001_initial.py was also not created automatically under migrations. -
Templatetag not working in Django 4.2 template IF condition
I have a Django 4.2 project. For an extra Templatetag I created this simple_tag. @register.simple_tag(takes_context=True) def user_help(context): # True if HELP is ON for user u = context['request'].user if u.needs_help: return True else: return False In the HTML template, I try to catch that Tag in an IF statement, to display help to the user, if needed, like this: <p>{% user_help %}</p> {% if user_help %} <h2>Some help text</h2> {% endif %} Although the p-statement shows True in the rendered template, the If condition part of the template is not shown...? What am I getting wrong here? -
CSRF cookie not set in Django POST
I have searched many of the SO questions and answers on this topic but cannot solve my problem. My js is based on this answer xxx.js import Cookies from 'js-cookie'; async function sendDataToAPI(uri, params) { let url = buildURI(uri, params); let endpoint = `${process.env.API_DOMAIN}${url}/`; try { const response = await fetch(endpoint, { method: "POST", credentials: 'include', headers: {'X-CSRFToken': Cookies.get('csrftoken')}, body: JSON.stringify({ data: params, }), } ); const data = await response.json(); return data; ... settings.py ... CSRF_TRUSTED_ORIGINS = [ 'http://localhost:8888' ] CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = ( 'http://localhost:8888', ) CORS_ALLOW_HEADERS = [ "X-CSRFToken", ] CORS_ALLOW_CREDENTIALS = True ... INSTALLED_APPS = [ ..., 'corsheaders', ... ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', ... ] I get ther error WARNING:django.security.csrf:Forbidden (CSRF cookie not set.) -
Serving a simple static asset in Django
I know this looks like a duplicate, but at this point I must have seen and tried every other solution to no avail, so I'm adding my question to the long list of existing questions in this vein. I don't have a ton of experience with Django, but I have an API on v3.2.16 of the framework to which I'd like to inject a static version file that I can reach through the browser. As this is an API, there are no other static assets that need to be served so I may not need the full django.contrib.staticfiles treatment (although I have tried it). What I'm looking for is the simplest possible way that I can create a directory from which Django will be able to serve a single static asset that I'll place during the application's build process. I've tried a bunch of staticfiles stuff over the last day or so, but am currently trying a simple implementation of: STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(settings.SITE_ROOT, 'assets'), ) Where the settings.SITE_ROOT value is /code on my container and /code/assets exists on the server. No matter what solution I've tried - including setting the STATIC_ROOT to that same directory and …