Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Facing issue in websocket in djagno
We are trying to show web pop-up on my web application when notification api call receive from any where, We implement Web socket communication in api and web app but after estable connectivity not able to send data on web serve. -
data not shown in BOTH database and webpage
Hi I am making a CRUD project of shopping based on models Products,categories,sub categories,size,colors.I am currently doing CRUD of SUBcategories which is connected to categories via foreign key. I am trying to insert data into the web page and the database but it isnt coming below is the model of sub_categories class SUBCategories(models.Model): category_name = models.ForeignKey(Categories,on_delete=models.CASCADE) sub_categories_name = models.CharField(max_length=20) sub_categories_description = models.CharField(max_length=20) isactive = models.BooleanField(default=True) def __str__(self): return self.categories_name below are the show functions and insert functions of sub categories def show_sub_categories(request): showsubcategories = SUBCategories.objects.filter(isactive=True) #print(showsubcategories) serializer = SUBCategoriesSerializer(showsubcategories,many=True) print(serializer.data) return render(request,'polls/show_sub_categories.html',{"data":serializer.data}) def insert_sub_categories(request): if request.method == "POST": insertsubcategories = {} insertsubcategories['sub_categories_name']=request.POST.get('sub_categories_name') insertsubcategories['sub_categories_description']=request.POST.get('sub_categories_description') form = SUBCategoriesSerializer(data=insertsubcategories) if form.is_valid(): form.save() print("hkjk",form.data) messages.success(request,'Record Updated Successfully...!:)') print(form.errors) return redirect('sub_categories:show_sub_categories') else: category_dict = Categories.objects.filter(isactive=True) category = CategoriesSerializer(category_dict,many=True) hm = {'context': category.data} print(hm) # print(form.errors) return render(request,'polls/insert_sub_categories.html',hm) else: category_dict = Categories.objects.filter(isactive=True) category = CategoriesSerializer(category_dict,many=True) hm = {'context': category.data} print(hm) return render(request,'polls/insert_sub_categories.html',hm) below is the show and insert pages of sub categories {% for result in data %} <tbody> <tr> <td><b>{{result.sub_categories_name}}</b></td> <td><b>{{result.sub_categories_description}}</b></td> <td style="position: relative;left:50px;"> <a href="sub_categories/edit_sub_categories/{{result.id}}"> <button class="btn btn-primary"> <i class="fa-solid fa-pen-to-square">EDIT</i> </button> </a> </td> <td> <a href="{% url 'sub_categories:delete_sub_categories' result.id %}" onclick="return confirm('Are You Sure you want to delete?')"> <button class="btn btn-danger"> <i class="fa-solid … -
Logic for Sortable table using Drag and Drop in Django
I am trying to create function for the Sortable Table. in which i am updating the position of the ids as per the given request: def put(self, request): max_len = Device.objects.count() ids = int(request.query_params.get('id')) temp = ids old = int(request.query_params.get('old')) new = int(request.query_params.get('new')) if new == old: return Response("both are equal can't go ahead") elif new > max_len: return Response("Invalid Position") elif old < new: t = Device.objects.get(id=ids) t.position = 0 print("new position Updated to 0") t.save() for i in range(old + 1, new + 1, 1): ids = ids + 1 print(ids) t = Device.objects.get(id=ids) print(t) t.position = t.position - 1 print(t.position) t.save() print(i, "value saved") t = Device.objects.get(id=temp) t.position = new print("new position Updated with ", t.position) t.save() print("new position saved") return Response("old < New") elif old > new: t = Device.objects.get(id=ids) t.position = 0 print("new position Updated to 0") t.save() for i in range(old - 1, new - 1, -1): ids = ids - 1 print(ids) t = Device.objects.get(id=ids) print(t) t.position = t.position + 1 print(t.position) t.save() print(i, "value saved") t = Device.objects.get(id=temp) t.position = new print("new position Updated with ", t.position) t.save() print("new position saved") return Response("old > New") Need help to make it more efficient, … -
How to get User instance in Django tests.py?
I'm a beginner in Django, I created a simple ecommerce app and I'm writing some tests in tests.py. I'm trying to write a test which check the correct creation of an OrderItem, but I don't know how to obtain an user instance. Should I check the logged in user or the existence of the user is enough? This is my store/models.py: from tkinter import CASCADE from django.db import models from django.conf import settings class Item(models.Model): name = models.CharField(max_length=50) price = models.FloatField() def __str__(self): return self.name class OrderItem(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) def __str__(self): return f"{self.quantity} of {self.item.name}" @property def get_total_price(self): return self.quantity*self.item.price And this store/tests.py: def create_item(name='cintura', price=10): return Item.objects.create(name=name, price=price) def get_user(): return User.objects.get(username='foo') def create_orderitem(quantity=2, user=get_user(), ordered=False): item = create_item() return OrderItem.objects.create(item=item, quantity=quantity, user=user, ordered=ordered) class OrderItemModelTest(TestCase): def test_orderitem_creation(self): order_item = create_orderitem() self.assertFalse(order_item.ordered) self.assertGreater(order_item.quantity, 0, 'Quantity must be > 0') #put here user check This is the error: django.db.utils.IntegrityError: The row in table 'store_orderitem' with primary key '1' has an invalid foreign key: store_orderitem.user_id contains a value '1' that does not have a corresponding value in auth_user.id. -
Django sitemap xml
How can i create django sitemap xml with all sub sitemaps with django pagination prefix? Or the 2nd question - how can i ping to google all paginating sitemap. For example 1st question result: <sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <sitemap> <loc>http://127.0.0.1:8000/sitemap-movies.xml</loc> </sitemap> <sitemap> <loc>http://127.0.0.1:8000/sitemap-movies.xml?p=2</loc> </sitemap> </sitemapindex> or <?xml version="1.0" encoding="UTF-8"?> <sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <sitemap> <loc>http://www.example.com/sitemap1.xml.gz</loc> </sitemap> <sitemap> <loc>http://www.example.com/sitemap2.xml.gz</loc> </sitemap> </sitemapindex> -
Django-React app search bar implementation
I want to implement a search bar on one of my pages in the Django-React app. I am a complete newbie in React and I am struggling with achieving the desired results. Basically, I created an endpoint on the backend to filter query results. Works fine in Insomnia. Now I wish to do the same on the frontend. my code so far: import React, {Component} from "react"; import {Col, Container, Row} from "reactstrap"; import SomeList from "./SomeList"; import NewSomeModal from "./NewSomeModal"; import axios from "axios"; import {BEARER_TOKEN, SOME_API_URL} from "../../constants"; const headers = { 'Content-Type': 'application/json', 'Authorization': BEARER_TOKEN }; class Some extends Component { state = { someArray: [], query: "" }; componentDidMount() { this.resetState(); } getSomeQuery = () => { axios.get(SOME_API_URL + `search?q=${this.state.query}`).then(res => this.setState({results: res.data})); }; resetState = () => { this.getSomeQuery(); }; render() { return ( <Container> <Row> <Col> <NewSomeModal create={true} resetState={this.resetState}/> </Col> </Row> <Row> <Col> <SomeList someArray={this.state.results} query={this.state.query} resetState={this.resetState} /> </Col> </Row> </Container> ); } } export default Some; This is where I create a table: import React, {Component} from "react"; import {Table} from "reactstrap"; import NewSomeModal from "./NewSomeModal"; import ConfirmRemovalModalSome from "./ConfirmRemovalModalSome"; class SomeList extends Component { handleChange = (e) => { this.setState({query: this.search.value}, () … -
Fixture not found within app tests by seen in pytest --fixtures
Are fixtures in conftest.py usable throughout and entire django project? For example I have this conftest.py located in root/fixtures from accounts.models import User from factories import UserFactory import pytest from pytest_factoryboy import register register(UserFactory) # user_factory @pytest.fixture def new_user(db, user_factory) -> User: user = user_factory.create() # Save user to test database return user However, I am getting this error when running pytest for my test in accounts/tests.py from accounts.models import User import pytest def test_new_user(new_user): print(new_user.email) count = User.objects.all().count() assert count == 1 def test_new_user(new_user): E fixture 'new_user' not found > available fixtures: _dj_autoclear_mailbox, _django_clear_site_cache, _django_db_helper, _django_db_marker, _django_set_urlconf, _django_setup_unittest, _fail_for_invalid_template_variable, _live_server_helper, _session_faker, _template_string_if_invalid_marker, admin_client, admin_user, async_client, async_rf, cache, capfd, capfdbinary, caplog, capsys, capsysbinary, client, db, django_assert_max_num_queries, django_assert_num_queries, django_capture_on_commit_callbacks, django_db_blocker, django_db_createdb, django_db_keepdb, django_db_modify_db_settings, django_db_modify_db_settings_parallel_suffix, django_db_modify_db_settings_tox_suffix, django_db_modify_db_settings_xdist_suffix, django_db_reset_sequences, django_db_serialized_rollback, django_db_setup, django_db_use_migrations, django_mail_dnsname, django_mail_patch_dns, django_test_environment, django_user_model, django_username_field, doctest_namespace, factoryboy_request, faker, live_server, mailoutbox, monkeypatch, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, rf, settings, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory, transactional_db > use 'pytest --fixtures [testpath]' for help on them. However, when I run pytest --fixtures I see --------------------------------------------------------- fixtures defined from factories.conftest --------------------------------------------------------- new_user -- factories/conftest.py:25 no docstring available -
Date lte filter in django and date localization
I am trying to get objects from django ORM upto a certain date from a DataFrame df12 which looks like this : Date Warehouse 33 2022-06-20 Delhivery Goa Warehouse 34 2022-07-04 Delhivery Goa Warehouse 35 2022-07-05 Delhivery Goa Warehouse Mu Code: for index, row in df12.iterrows(): print("date", row['Date']) print("warehouse", row['Warehouse'].split(" ")[1]) obj = RFIDTagging.objects.filter(date__lte=row['Date'], owner__in=emp) The problem is that the above code excludes objects created on 2022-07-05 which is stored in the ORM like the following: 2022-07-05 12:05:06.274462 +00:00 2022-07-05 12:05:06.227598 +00:00 2022-07-02 18:39:11.648968 +00:00 2022-07-02 18:39:11.590210 +00:00 I tried converting the Date column like the following df12["Date"] = df12["Date"].tz_localize("Asia/Kolkata").tz_convert("UTC") but getting the following error: TypeError: index is not a valid DatetimeIndex or PeriodIndex -
how to send data from websocket to django consumer.py
I am trying to send current user as argument in websocket on connect but I am unable to receive the user in websocket connect function. please find the code below. consumer.py import asyncio from channels.consumer import AsyncConsumer from channels.db import database_sync_to_async class ChatConsumer(AsyncConsumer): async def websocket_connect(self, event): self.connected = True print("connected", event) await self.send({ "type": "websocket.accept" }) while self.connected: User=event["username"] await asyncio.sleep(2) apps = await database_sync_to_async(list)(User.objects.filter(user=User) listo=[] for app in apps: username = app.username id = app.id outputDict = {"id":id,"username":username} listo.append(outputDict) await self.send({ 'type': 'websocket.send', 'text': json.dumps(listo), }) async def websocket_receive(self, event): print("receive", event) async def websocket_disconnect(self, event): print("disconnected", event) self.connected = False javascipt: var socket = new WebSocket('ws://' + window.location.host + '/ws/notif/' + socketCode + '/'); socket.onmessage = function(e){ console.log("message", e.data); }; socket.onopen = function(e){ socket.send(JSON.stringify({ 'user': 1003, })) console.log("open", e); }; socket.onerror = function(e){ console.log("error", e) }; socket.onclose = function(e){ console.log("close", e) }; } Please help me how to get data from JavaScript to websocket connect function -
Passing Data to D3.js with Django Backend
I want to build a line chart following the code here. I've made slight change to the data being passed with contains epoch time and a closing price. Following is the code {% load static %} <html> <script src="https://d3js.org/d3.v4.js"></script> <body> <h1> Hello! </h1> <div id="my_dataviz"></div> </body> <script> // set the dimensions and margins of the graph var margin = {top: 10, right: 30, bottom: 30, left: 60}, width = 460 - margin.left - margin.right, height = 400 - margin.top - margin.bottom; // append the svg object to the body of the page var svg = d3.select("#my_dataviz") .append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); //Read the data var d = { "Date":{ "0":1641168000000, "1":1641254400000, "2":1641340800000 }, "Close":{ "0":182.01, "1":179.7, "2":174.92 } }; // When reading the csv, I must format variables: d3.json(d, function(d){ return { date : d3.timeParse("%s")(d.Date), value : d.Close } }, // Now I can use this dataset: function(data) { // Add X axis --> it is a date format var x = d3.scaleTime() .domain(d3.extent(data, function(d) { return d.date; })) .range([ 0, width ]); svg.append("g") .attr("transform", "translate(0," + height + ")") .call(d3.axisBottom(x)); … -
{% csrf_token %} is empty string but {{ csrf_token }} returns a value - Django
I have to submit a form via POST method. I added to my html form the {% csrf_token %} tag but from the DOM I'm getting this: <input type="hidden" name="csrfmiddlewaretoken" value=""> But if I type {{ csrf_token }} in the template I can see the value. Why can't I set my token in the form? This is my form: <form action="{% url 'aj_upload_file' %}" method="POST"> {% csrf_token %} <a id="upload-file-btn" href="javascript:;" class="btn btn-success mr-2"> <i class="fa fa-upload" aria-hidden="true"></i> </a> <input class="d-none" multiple type="file" id="upload-file"> </form> Thank You. -
dictionary not coming in for loop despite correct syntax
I am doing crud project which has models PRoducts,categories,sub categories ,color,size. I am trying to get a django dropdown using SERIALIZERS and have connect categories and subcategories via foreignkeys below are the models below is the function of isnerting in views.py of sub categories and below is the html code for the dropdown using for loops I also tried {{c}} even that didnt work the drop down still doesnt have any options,where am I going wrong? -
How to access a foreign key related field in a template when using Django model form
My Objective Access the field name in the Parent Model ParentModel and display its content in a form instance in the template. For example, let the field parent be a foreign key in the ChildModel as described below. What I have tried Access the parent field in the form as {{ form.parent.name }} in the template Errors received Tried looking up form.parent.name in context models.py class ParentModel(models.Model): name = models.CharField() class ChildModel(models.Model): parent = models.ForeignKey(ParentModel) forms.py class ChildModelForm(ModelForm): class Meta: model = ChildModel fields = '__all__' widgets = {'parent': forms.Select(),} views.py def childView(request, pk): template = 'template.html' child = ChildModel.objects.get(parent=pk) form = ChildModelForm(instance=child) if request.method == 'POST': form = ChildModelForm(request.POST, instance=child) if form.is_valid(): form.save() else: form = ChildModelForm(instance=child) context = {'form': form, } return render(request, template, context) template.html <form method="POST" action=""> {% csrf_token %} {{form.parent.name}} <button type="submit">Save</button> </form> Now the child model form displays pk I want to display the name of the parent field I have also tried using this Django access foreignkey fields in a form but it did not work for me. -
DRF ManyToMany instances add not create
I have the following code of my model: class Recipe(BaseModel): """ Recipe model class using for contains recipe, which can be sent to chat with coach. In text recipe contains RecipeStep. """ ingredients = models.ManyToManyField( Product, verbose_name=_("ingredients"), related_name="ingredients" ) portion_size = models.PositiveSmallIntegerField( _("portion size") ) # TODO: add "add_to_meal" logic (user can add recipe to his meal). # it can be reached by using M2M with user and creating new relation for # user and recipe on user click on special button. def __str__(self) -> str: return f"recipe \"{self.title}\"" def __repr__(self) -> str: return f"Recipe({self.pk=}, {self.title=}, {self.is_published=})" class Meta: verbose_name = _("recipe") verbose_name_plural = _("recipes") BaseModel is abstract class, that has basic structure of Article-like models (title, description, published_at, etc.). And the following code of serializers for model: class RecipeSerializer(serializers.ModelSerializer): id = serializers.UUIDField(read_only=True) title = serializers.CharField(min_length=1, max_length=200, required=True) ingredients = ProductSerializer(many=True, read_only=False) portion_size = serializers.IntegerField(min_value=0, required=True) is_published = serializers.BooleanField(required=False, default=False) publish_date = serializers.DateField( allow_null=True, required=False, read_only=True ) image_add_id = serializers.UUIDField(required=True) def create(self, validated_data): validated_data.pop('image_add_id', None) return super().create(validated_data) class Meta: model = Recipe fields = "__all__" I need to create Recipe with passing list of existing ingredient pks, and not create new ingredients like: { ... "ingredients": [ "d6c065a2-7f80-47f3-8c0e-186957b07269", "4b8359d2-073a-4f41-b3cc-d8d2cfb252d5", "b39e4cc2-18c3-4e4a-880a-6cb2ed556160", … -
ModuleNotFoundError: No module named 'app' on new Django installation
I am trying to set up a simple Django==4.0.6 dev environment on my Ubuntu 20.04. I'm creating a project folder, create and activate a venv first. Then I'm installing Dajngo using pip. I'm then creating a new project in the very same directory and then for testing this out, run the usual python manage.py command. Here's a quick list of commands I am using: mkdir project && cd project python3 -m venv venv source venv/bin/activate pip install django==4.0.6 django-admin startproject major . python manage.py migrate But I'm getting the following error: Traceback (most recent call last): File "/project/venv/lib/python3.8/site-packages/django/core/management/base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "/project/venv/lib/python3.8/site-packages/django/core/management/base.py", line 460, in execute output = self.handle(*args, **options) File "/project/venv/lib/python3.8/site-packages/django/core/management/base.py", line 95, in wrapped saved_locale = translation.get_language() File "/project/venv/lib/python3.8/site-packages/django/utils/translation/__init__.py", line 210, in get_language return _trans.get_language() File "/project/venv/lib/python3.8/site-packages/django/utils/translation/__init__.py", line 65, in __getattr__ if settings.USE_I18N: File "/project/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 87, in __getattr__ self._setup(name) File "/project/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 74, in _setup self._wrapped = Settings(settings_module) File "/project/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 183, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, … -
Javascript is not working properly inside djagno project
While my code is working when used outside of a Django project, when I place it inside one it's acting strange. More specifically, the document object does not have a body, but only the head of my html. Thus I am not able to access its classes. My guess is that something's wrong in the linking between the html and js files. settings.py STATIC_URL = 'static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>index.html</title> {% load static %} <link rel="stylesheet" href="{% static 'style.css' %}"/> <script src="{% static 'script.js' %}"></script> </head> <body> HelloWorld! </body> </html> script.js console.log(document.getElementsByTagName('html')[0].innerHTML) The return of script.js: <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>index.html</title> <link rel="stylesheet" href="/static/style.css"> <script src="/static/script.js"></script></head> -
Django: Use a read-only database within django test suite
In my Django project, I'm using two databases, one of which is my own PostgreSQL database where I have the read and write rights, and the other one is an external PostgreSQL database in which I only have read-only rights. It works perfectly in the context of the project, I can access both databases. However when I use the Django test suite using ./manage.py test, Django is trying to create a test database for the external database. I don't want that, I want to be still able to access the external PostgreSQL database within the test suite without needing to create a test database on this external PostgreSQL database. It also gives me this error: /usr/local/lib/python3.10/site-packages/django/db/backends/postgresql/base.py:323: RuntimeWarning: Normally Django will use a connection to the 'postgres' database to avoid running initialization queries against the production database when it's not needed (for example, when running tests). Django was unable to create a connection to the 'postgres' database and will use the first PostgreSQL database instead. But I don't have access to the 'postgres' database in the external database and I don't want to run initialization queries against it. Here is the configuration for the external read-only database connection: DATABASES["aact"] = { … -
Accepting JSON format, parsing him and having endpoints to accessing the data (Django)
Hello I want to ask how can I create models and API in Django that accepts JSON format, parsing it and then access it in some of the endpoints. I need to have [POST] endpoint /import which will accept the data and parse them, [GET] /detail/<name_of_the_model> will show list of records from the JSON file based on the name of the model and finally /detail/<name_of_the_model>/<id> which shows all the data for the exact record from the JSON file. I think I can manage things with the models/modelForms but I can't figure out how to implement it with JSON. Thanks for any help. -
Django. How to update form field on other field change without Javascript?
Is it possible to update form field when user changes value of the other field without using Javascript? class PurchaseOrderItemForm(forms.ModelForm): class Meta: model = PurchaseOrderItem fields = [ 'product', 'price_per_unit', 'quantity', ] class PurchaseOrderItemCreateView(LoginRequiredMixin, CreateView): model = PurchaseOrderItem template_name = 'purchases/purchase_order_item_create.html' form_class = PurchaseOrderItemForm For example I want the price of the product to be set automatically when user selects a product from the list. Or is JS mandatory in this case? -
Redirect urls in django
We have a blog created with Django 4. And have articles where for each article exists a url like this www.example.com/id/slug but for some of them we changed the id and we want to redirect the old urls to the new one. For example we want to turn www.example.com/2/slug1 to www.example.com/56/slug1 How can we do this in Django 4? -
Gunicorn (Django + NGINX) keeps date till Gunicorn restart
I'm moving Django apps from Apache2 to Nginx/Gunicorn and have one problem. I used simple tutorial from Digital Ocean to setup Nginx/Gunicorn environment apps and all is steady, working fine. But i found out i have some strange problem with date. It looks like all my apps run the same day, the day app was started/restarted. Queries to DB for yesterday items return 0 rows. When i reset gunicorn or run the app via ./manage.py runserver all works as expected. Same code using old server (running Apache2) works fine too. So there is no problem with the code, but config issue. Somehing like Gunicorn freezes in time(date) and needs to be regularly restarted? Or I'm missing something in my settings? My socket file: [Unit] Description=VKCRM [Socket] ListenStream=/run/vkcrm.sock [Install] WantedBy=sockets.target my service file: [Unit] Description=VKCRM daemon Requires=vkcrm.socket After=network.target [Service] User=www-data Group=www-data WorkingDirectory=/var/www/virtuals/crm/vkcrm ExecStart=/var/www/virtuals/crm/bin/gunicorn --access-logfile - --workers 1 --timeout 100 --bind unix:/run/vkcrm.sock vkcrm.wsgi:application [Install] WantedBy=multi-user.target Thanks for any help, it must be some basic settings stuff. Maybe restart Gunicorn each day, restart workers after jobs done or something like this? But can't find out what i'm missing. -
I get this error when I want to do makemigrations : 'PosixPath' object has no attribute 'startswith'
python manage.py makemigrations: Traceback (most recent call last): val = self._add_script_prefix(val) Development-/venv/lib/python3.9/site-packages/django/conf/init.py", line 135, in _add_script_prefix if value.startswith(('http://', 'https://', '/')): AttributeError: 'PosixPath' object has no attribute 'startswith' -
Session id and csrf token not set in cookie
I am using django as backend and react as frontend,in local the session auth working fine,but when I deploy in secure mode(https) csrf and sesion id is not set in the cookie,but I recieve the response header for set-cookie. This is my setings.py file CSRF_TRUSTED_ORIGINS = [ "https://'prod link'", 'http://localhost:3000', 'http://127.0.0.1:3000', ] # PROD ONLY CSRF_COOKIE_SAMESITE = 'None' SESSION_COOKIE_SAMESITE = 'None' CSRF_COOKIE_SECURE = True SESSION_COOKIE_SECURE = True ACCESS_CONTROL_ALLOW_ORIGIN = [ "https://'prod link'", 'http://localhost:3000', 'http://127.0.0.1:3000', ] CORS_ALLOWED_ORIGINS = [ "https://'prod link'", 'http://localhost:3000', 'http://127.0.0.1:3000', ] CORS_EXPOSE_HEADERS = ['Content-Type', 'X-CSRFToken'] CORS_ALLOW_CREDENTIALS = True Set-Cookie in network tab -
How to pass arbitrary Python object (e.g. InMemoryUploadFile) to a different Django view
This question will likely betray my inexperience in web development, so please let me know if I'm solving entirely the wrong problem. I'm building a web application where users are asked to upload a data file. After uploading, the users are shown some aggregate statistics of the data contained in the file to help catch any errors. The user can then confirm this is the right data. Only then will the file will be stored somewhere on other people's computers in the cloud. I Django, I have defined three views/templates: Upload: the template contains the form that allows the user to select a file to upload. Check: the template shows the aggregate statistics and contains a form with buttons to go back or confirm that the uploaded file is correct. Confirm: the page shows that the file was stored. The problem is that the file is uploaded in the Upload view/template; but I only want to determine the aggregate statistics on the Check page and store the file after the user has confirmed its aggregate statistics in the Check view/template. I'm not sure how I can pass the file (which will be an InMemoryUploadFile object) from the Upload view to … -
datatable with chartjs problem while changing row numbers
I'm trying to integrate datatable with chartjs, it works fine if i dont change the row numbers, or not do any filtration, from UI, when i change the row numbers for example, by default its 10, when i change it to 25, the charts also change, but when i move the mouse cursor to the chartjs canvas sometimes it shows the previous data(the 10 row data). how to fix it, or update the chartjs canvas data to the new Here is my code: $(document).ready(function(){ var list_daily_prices = document.getElementById('list_daily_prices') if(list_daily_prices){ $('#list_daily_prices').DataTable({ "serverSide":true, "processing":true, "ordering": false, "ajax":function(data,callback,settings){ $.get('/prices/daily/data',{ start:data.start, limit:data.length, filter:data.search.value, },function(res){ callback({ recordsTotal:res.length, recordsFiltered:res.length, data:res.objects }); }, ); }, "columns":[ {"data": "counter"}, {"data": function(data,type,dataToSet){ const date = new Date(data.day).toLocaleDateString('fr-CA') return date }}, {"data": "total_quantity"}, {"data": "total_price"}, {"data": "income"}, ], "drawCallback":function(settings){ var daily_date = [] var qnt = [] var total_price = [] var income = [] for(counter=0;counter<settings.aoData.length;counter++){ daily_date.push(new Date(settings.aoData[counter]._aData['day']).toLocaleDateString('fr-CA')) qnt.push(settings.aoData[counter]._aData['total_quantity']) total_price.push(parseFloat(settings.aoData[counter]._aData['total_price']).toFixed(2)) income.push(parseFloat(settings.aoData[counter]._aData['income']).toFixed(2)) } var dailyPriceCanvas = $('#list_daily_prices_charts').get(0).getContext('2d') var dailyPriceData = { labels: daily_date, datasets: [ { label:'quantity', data: qnt, backgroundColor : '#9D0CA6', }, { label:'total price', data: total_price, backgroundColor : '#1392BE', }, { label:'income', data: income, backgroundColor : '#00a65a', }, ] } var dailyPriceOptions = { responsive : true, maintainAspectRatio : …