Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
the administration site of django not fully presentable after copying my project on a linux server
it's the first time i see this thing , -when i go to the site of administration of django , there is no blue color everything is with white and black color and not presentable, -on my localhost everything is fine , this happened when i have copied my project django on a linux server. ps: the other templates(routes) that are linked to my project are fully presentable(there was the images and the colors..) (See the screenshoot of my administration site django please) I have tried to restart nginx and gunicorn by: sudo service nginx restart sudo service gunicorn restart but it's the same thing. Help please. Thanks in advance. -
Django runserver - Can you output the connecting IP to the console?
I am trying to capture the IP address of incoming connections to the console using the development webserver that comes with django (manage.py runserver 0.0.0.0:8000). Right now, I get the following output on requests: [24/Feb/2022 13:03:38] "GET /admin/aqww/ HTTP/1.1" 200 3223 Is there a way to get an incoming client IP address in there? For example, make it look something like the following? [24/Feb/2022 13:03:38 192.168.1.34] "GET /admin/aqww/ HTTP/1.1" 200 3223 Thanks -
Can I pass a list of objects into a session? Django/Python
I have data that does not need stored in a db. I have a list of results from an API that is made up of objects i created based off of what is returned by the api. I want to display results in an html table. When I paginate i lose all that data and want to pass the list of objects into the session to pass with each page. Is this possible? -
Why does my Django project somtimes not serve static files
Whenever I make a Django project sometimes the static files do not serve properly. I make sure that the files exist in the following format myapp/static/myapp. -
Django get the static files manifest storage URL in view when in DEV
One can get the static url in view with: from django.templatetags.static import static url = static('x.jpg') However during dev I use django.contrib.staticfiles.storage.StaticFilesStorage, and in production I use django.contrib.staticfiles.storage.ManifestStaticFilesStorage. How I have a build script that bundles some javascript modules files, the imports require the hashed urls, during DEV. Is there a way to calculate the hashed file name when the django settings.STATICFILES_STORAGE is StaticFilesStorage? The below code is what I came up with, but sometimes it gives the wrong hash (collect static modifies the files (e.g. source code map urls), so I think that changes the hash of the staic file if it references another static file): from django.contrib.staticfiles import finders from django.contrib.staticfiles.storage import staticfiles_storage from django.core.files.storage import get_storage_class from django.template import loader # Here spath = static path, and fpath = file path, mpath = manifest (hashed) path # fname = filename def spath_to_fpath(spath): return finders.find(spath) def spath_to_mpath(spath): fpath = spath_to_fpath(spath) manifest_storage = get_storage_class( 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage' )() # location is the fpath that spath is relative too, get the fpath and right trim the spath manifest_storage.location = fpath.rsplit(spath)[0] app, name = spath.rsplit('/', 1) # The filename hashed_fname = manifest_storage.hashed_name(name, filename=spath) # filename arg takes a spath mpath = f"/static/{app}/{hashed_fname}" # … -
How can I send React post requet with file data to an API?
Here I want to register user with image so I want to pass both image and name in my formdata. I am able to upload the file using some guideline (I am not good with react) but I am not able to pass the input name with my formdata. which procedure to follow? import React from 'react' import { useState, getState } from "react"; import axios from "axios"; import { useDispatch, useSelector } from 'react-redux' function VendorRegistration() { const [file, setFile] = useState(null); const UPLOAD_ENDPOINT = "http://127.0.0.1:8000/api/orders/vendor/register/"; const handleSubmit = async e => { e.preventDefault(); //if await is removed, console log will be called before the uploadFile() is executed completely. //since the await is added, this will pause here then console log will be called let res = await uploadFile(file); console.log(res.data); }; const userLogin = useSelector(state => state.userLogin) const { userInfo } = userLogin const uploadFile = async file => { const formData = new FormData(); formData.append("avatar", file); return await axios.post(UPLOAD_ENDPOINT, formData, { headers: { "content-type": "multipart/form-data", "Authorization" : `Bearer ${userInfo.token}`, } }); }; const handleOnChange = e => { console.log(e.target.files[0]); setFile(e.target.files[0]); }; return ( <form onSubmit={handleSubmit}> <h1>React File Upload</h1> <input type="file" onChange={handleOnChange} /> <input type="name" /> <button type="submit">Upload File</button> … -
How to have different login pages for same authentication model in Django?
I have one Django user model (with a custom user manager) but two different user types, namely Store and Customer, to handle authentication: authentication/models.py class User(AbstractBaseUser, PermissionsMixin): ... # checks if user is associated with a store object def is_store(self): return hasattr(self, 'store') # checks if user is associated with a customer object def is_customer(self): return hasattr(self, 'customer') stores/models.py class Store(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, verbose_name=_('user'), on_delete=models.RESTRICT, primary_key=True) ... def clean(self): # validates that the selected user doesn't belong to a customer object if self.user.is_customer(): raise ValidationError({'user': _('This user is already associated with a customer.')}) customers/models.py class Customer(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, verbose_name=_('user'), on_delete=models.CASCADE, primary_key=True) ... def clean(self): # validates that the selected user doesn't belong to a store object if self.user.is_store(): raise ValidationError({'user': _('This user is already associated with a store.')}) Now, the stores and customers should use two different websites to login in i.e. stores will use admin.domain.com while customers will simply use domain.com. If a store is logged into admin.domain.com, will it also show that he is logged in when he visits domain.com? If so, how can I prevent this and isolate these two models to specific sites, while using the same authentication model and methods? -
Can someone help me optimize my Django queries/project structure?
I have created a new Django project and it works fine, but I'm sure there is a better way to do the following and thought of asking. So my main issue is on the template where I have to call the same for loop twice. The one time to include a clinic of the url as you can see on the urls.py, and the other time to show the rest of clinics that are available in the same day. urls.py path('onhold-hospitals/<slug:region_slug>/<slug:clinic_slug>/results/<yyyy:date>/', views.onhold_hospital_results, name='date-clinics-view-results') I'm using this statement in the template: {% for hospital in available_hospitals %} {% if hospital.onhold_date|date == default_date|date and hospital.clinic == clinic%} <h5>Name: {{ hospital.hospital}} - Name: {{ hospital.onhold_date}} - Clinic: {{ hospital.clinic}}</h5> {% endif %} {% if hospital.onhold_date|date == default_date|date and hospital.clinic != clinic%} <p>Other clinics available on the same day: {% for hospital in available_hospitals %} {{hospital.clinic}} {% endfor %} {% endif %} {% endfor %} And here are my core model: class Schedule(models.Model): onhold_hour = models.CharField(max_length=50, blank=True, null=True) onhold_date = models.DateField(default=date.today) region = models.ForeignKey(Region, on_delete=models.CASCADE, null=True, related_name="area") hospital = models.ForeignKey(Hospital, on_delete=models.CASCADE, null=True, related_name="available_hospital") clinic = models.ForeignKey(Clinic, on_delete=models.CASCADE, null=True, related_name="clinic_type") all these are being returned from the following views.py: def onhold_hospital_results(request, region_slug, clinic_slug, **date_filters): clinic … -
How to make Custom Registration Form in HTML integration with Django without using Django forms
I want to take specific inputs from user during registration and map with authentication mechanism of Django.This page will be displayed to super users only after login and will be available as a menu as register user.I don't want to customize admin page and use inbuilt form functionality of Django. Please guide. registration <body bgcolor="Lightskyblue"> <br> <br> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <label> Party name </label> <input type="text" name="partyname" size="100"/> <br> <br> <label> Party Employee Number: </label> <input type="text" name="partyno" size="100"/> <br> <br> <label> Party category: </label> <input type="text" name="partycategory" size="100"/> <br> <br> <label> Party type: </label> <input type="text" name="partytype" size="100"/> <br> <br> <label> Party subtype: </label> <input type="text" name="partysubtype" size="100"/> <br> <br> <label> Party spoc: </label> <input type="text" name="spoc" size="100"/> <br> <br> <label> Party email: </label> <input type="text" name="partyemail" size="100"/> <br> <br> <label> Party Mobile: </label> <input type="text" name="partymob" size="100"/> <br> <br> <label> Party address: </label> <input type="text" name="partyadd" size="100"/> <br> <br> <label> Party level: </label> <input type="text" name="partylevel" size="100"/> <br> <br> <label> Party State: </label> <input type="text" name="partystate" size="100"/> <br> <br> <input name='uploaddoc' type="submit" value="Uploaddoc" > </form> </body> models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) party_emp_number=models.CharField(max_length=100, blank=True, null=True) party_category=models.CharField(max_length=100, blank=True, null=True) party_type=models.CharField(max_length=100, blank=True, null=True) party_subtype=models.CharField(max_length=100, blank=True, null=True) … -
search_phase_execution_exception, failed to create query
I am using elasticsearch-dsl in my django project. Elasticsearch is totally new for me and at some point i got this error: error So i started debugging and removing some part of my code. But here i am my code has become extremely simple but i still don't know why i get this error. The code: import re from django.conf import settings from elasticsearch_dsl.query import Bool, Match, MatchPhrase, Nested from .documents import RubricPageDocument def _build_match_query(query, field): if len(query) <= 4: return Match(**{field: {'query': query}}) if re.match('^".*"$', query): return MatchPhrase(**{field: {'query': query}}) return Match(**{field: {'query': query, 'fuzziness': 'AUTO'}}) def search_query_in_rubric_pages(query): q_title = _build_match_query(query, 'title') q = q_title s = RubricPageDocument.search().query(q) response = s.execute() # error raise on this line return [_format_hit(hit, 'rubric') for hit in response] def search_query(query): """ search in elastic search index for rubric pages * query (str): the query """ page_hits = search_query_in_rubric_pages(query) return { 'hits': page_hits, } Please help me -
Django : Re-login problems with msal when we are already authenticated
I am a newbee in Django. I am trying to do my first Dashboard. For the authentication, I am using msal and the graph tutorial from Microsofs : https://docs.microsoft.com/en-us/graph/tutorials/python I did a different template for my app but used the function from the tutorial to login. Then I tried to do my first application that is to upload a file. When I click on the link to go the app, I restart the process of login and after it redirect me to the home page. I do not get why it redirects me because I should be authenticated. Below is my html code/template that splits the login page and the dashboard when we are authenticated. Home.html <!DOCTYPE html> <html lang="en"> {% load static %} <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>Document</title> <!-- Boxicons CSS --> <link href='https://unpkg.com/boxicons@2.1.1/css/boxicons.min.css' rel='stylesheet'> </head> <body> {% if user.is_authenticated %} <link rel="stylesheet" href="{% static 'style.css' %}"> <div class="sidebar close"> <div class="logo-details"> <a href="{% url 'home' %}"> <img src="{% static 'image/logo.svg' %}" alt="" > </a> <!-- <span class="logo_name">CodingLab</span> --> </div> <ul class="nav-links"> <li> <a href="#"> <i class='bx bx-grid-alt' ></i> <span class="link_name">Dashboard</span> </a> </li> <li> <div class="iocn-link"> <a href="#"> <i class='bx bx-buildings'></i> <span class="link_name">Organisation</span> … -
can I generate ERD using .sql file in python?
ERD generator using python scripts in python -
How to create pivot tables with model_bakery
I want to create a baker recipe who create one object, objects from a pivot table and links everything well. An incident is created when cells of a technology (2g, 3g, 4g, 5g) are down, but not all technologies are impacted. So we have a pivot table to manage this. My goal is to avoid writing code duplicates and manage this with a simple baker.make_recipe("incidents.tests.incident_with_multiple_impacts") to create an incident and 4 different impacts (technologies are created in fixtures) # incident/models/incident.py class Incident(models.Model): impacted_technologies = models.ManyToManyField( Technology, through="IncidentIncidentImpactedTechnologies" ) # network/models/technology.py class Technology(models.Model): alias = models.CharField(max_length=2, unique=True, blank=False) # ie: "2G", "3G"... name = models.CharField(max_length=4, unique=True, blank=False) # incident/models/incident_technologies.py class IncidentIncidentImpactedTechnologies(models.Model): incident = models.ForeignKey( to="incident.Incident", on_delete=models.CASCADE, related_name="technology_impacts", ) technology = models.ForeignKey( to="network.Technology", on_delete=models.CASCADE, related_name="impacting_incidents", ) During my researches, I writed code above (I want to keep first recipes to reuse them later): def get_technology(key=None): if key: return Technology.objects.get_by_alias(key) # to get it with "2G" return random.choice(Technology.objects.all()) incident_assignation = Recipe( Incident, # few other fields ) impacted_techno = Recipe( IncidentIncidentImpactedTechnologies, incident=foreign_key(incident_assignation), technology=get_technology, # Default, take random technology # Fields describing a NO_IMPACT on this techno ) impacted_techno_cell_down = impacted_techno.extend( # Fields describing a CELL_DOWN impact on this techno ) impacted_techno_degraded = impacted_techno.extend( … -
user login either email or username in Django rest framework with simplejwt authentication
I'm using: Django==3.2.9 djangorestframework==3.12.4 djangorestframework-simplejwt==5.0.0 I want to make a login system that takes either username or email and password as a parameter from a user. After that authenticate a user with those credentials and provide access & refresh token as a response. And I want to use access and refresh tokens use the JWT token system of djangorestframework-simplejwt. -
Looping problem with defauldict in Django templates
On my Django , i used defauldict on my views, and to give a structure I put this code in my template , but it s not working nothing happen in my output What i need to change please ? I want to see in my web page something like this : .List in the file : value value1 value3 ... .List not in the file : value value value... .html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title> Dashboard Result</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script type="text/javascript"> $("#btnPrint").live("click", function () { var divContents = $("#dvContainer").html(); var printWindow = window.open('', '', 'height=400,width=800'); printWindow.document.write('<html><head><title> ListingCheckPDF</title>'); printWindow.document.write('</head><body >'); printWindow.document.write(divContents); printWindow.document.write('</body></html>'); printWindow.document.close(); printWindow.print(); }); </script> </head> <body style="margin-top: 30px; padding: 100px"> <h1> List </h1> <form id="form1"> <div id="dvContainer"> </div> <input type="button" value="Print Div Contents" id="btnPrint" /> </form> {% for key, value in results.items %} {{ item.key }} {{ item.value}} {% endfor %} {% autoescape off %}{{ output_df }}{% endautoescape %} </body> </html> views.py from django.shortcuts import render from django.core.files.storage import FileSystemStorage import pandas as pd import datetime from datetime import datetime as td import os from collections import defaultdict def home(request): if request.method == 'POST': uploaded_file = request.FILES['document'] uploaded_file2 = request.FILES['document2'] if uploaded_file.name.endswith('.xls'): savefile = … -
Why is my my related field not working properly? [Django]
I want to acheive: I have 2 Models Tag and Startup. my models.py file - from django.db import models from django_extensions.db.fields import AutoSlugField from django.db.models import CharField, TextField, DateField, EmailField, ManyToManyField class Tag(models.Model): name = CharField(max_length=31, unique=True, default="tag-django") slug = AutoSlugField(max_length=31, unique=True, populate_from=["name"]) def __str__(self): return self.name class Startup(models.Model): name = CharField(max_length=31, db_index=True) slug = AutoSlugField(max_length=31, unique=True, populate_from=["name"]) description = TextField() date_founded = DateField(auto_now_add=True) contact = EmailField() tags = ManyToManyField(Tag, related_name="tags") class Meta: get_latest_by = ["date_founded"] def __str__(self): return self.name When creating a startup, I have a dropdown list of created Tags which I want to relate to my Startup that I am creating. When I am posting the data - { "name": "Startup4", "description": "TestStartup", "contact": "startuptest@gmail.com", "tags": [ { "url": "http://127.0.0.1:8000/api/v1/tag/first-tag/", "name": "First Tag", "slug": "first-tag" }, { "url": "http://127.0.0.1:8000/api/v1/tag/second-tag/", "name": "Second Tag", "slug": "second-tag" }, { "url": "http://127.0.0.1:8000/api/v1/tag/third-tag/", "name": "Third Tag", "slug": "third-tag" } ] } A startup is created but the tags field remains empty. No Tags are related. My serializers.py file - from rest_framework.serializers import HyperlinkedModelSerializer, PrimaryKeyRelatedField, ModelSerializer from .models import Startup, Tag class TagSerializer(HyperlinkedModelSerializer): class Meta: model = Tag fields = "__all__" extra_kwargs = { "url": { "lookup_field": "slug", "view_name": "tag-api-detail" } } class … -
using inline javascript inside a python loop
I have a list of entries. Insider the list of entries I have a link to individual entries. I have an update form that updates one field. I want to open the update form inside a new window. The user then submits the form is directed to a success page which currently has a timed close. The issue I am encountering is with the inline javascript which opens the form in a new window. When I attempt to assign the kwarg on the url it the javascript does not change with each entry in the list. I have limited javascript, and jquery knowledge. I just want the javascript to open a new window for each update form. I have included the template below. <thead> <tr> <th>Script No.</th> <th>Entered on</th> <th>Patient</th> <th>Email</th> <th>Product</th> <th>Form</th> <th>Units</th> <th>Dispensing Price</th> <th>Status</th> <th>Dispatch Date</th> <th>Entered by</th> <th></th> </tr> </thead> <tbody> {% for script in scripts %} <tr> <td>{{script.pk}}</td> <td>{{script.entered_on}}</td> <td>{{script.patient}}</td> <td>{{script.patient.email}}</td> <td>{{script.product}}</td> <td>{{script.product.form.description}}</td> <td>{{script.quantity}}</td> <td>$&nbsp;{{ script.dispensing_price }}</td> {% if script.dispatch_date is not none %} <td>{{script.get_script_status_display}}</td> {% else %} <td><a href = "{% url "script:script_update_status" script.pk %}">{{script.get_script_status_display}}</a></td> {% endif %} <td><a href ="#" onclick="updateStatus()" style="float:right;"> <script>var url = "{% url "script:script_update_status" script.pk %}"; function updateStatus() {var … -
To pass the Response from the nested function `Django REST framework`
I am using python django with Django REST framework It can return the Reponse to the browser like this, in the views.py from rest_framework.response import Response @api_view(['GET']) def get_by(request): res = {"test":"answer"} return Response(res) I want to pass the Response to the browser where nested function from rest_framework.response import Response @api_view(['GET']) def get_by(request): x(t) def x(): #error happens here!! res = {"error":"error happens!!"} return Response(res) in this case, it is simple, I can return the error to the first function and first function can return the error Response. but when you have three four,five nested function? What is the best practice? -
Setting up a good python development environment/editor
I've been developing a project web application in VSCode, using eslint and prettier. It's great and saves me a lot of time. I'm trying to setup a similar environment for a django project, but I'm either lacking a lot of features (no automatic linting, no intellisense) or Pylance is throwing errors like Expected class type but received "LazySettings" Cannot access member "XX" for type "YY" I've tried using the template (https://github.com/wemake-services/wemake-django-template) to combat some of these issues, but I end up in the same place. It feels like I'm lacking some fundamental knowledge. I am able to run the server without issues. Using python 3.9.10. Any suggestions (new editor, vscode settings, stubs) would be very appreciated. -
Автозаполнение поля формы получая id вопроса django
Создаю свой форум. Пытаюсь сделать ответы на вопросы я сделал автозаполнение поле User_id в таблице Quetions и а таблице Answer user_id : models.py class Quetions(models.Model): User_id = models.ForeignKey (User,to_field='id',on_delete=models.DO_NOTHING,verbose_name='Пользователь',blank=True) category_id = models.ForeignKey (Category,to_field='id',on_delete=models.DO_NOTHING,verbose_name='Предмет') schoolclass = models.ForeignKey (SchoolClass,to_field='id',on_delete=models.DO_NOTHING,verbose_name='Класс') subject = models.CharField(max_length=255,verbose_name='Тема вопроса') text = models.TextField(verbose_name='Вопрос') img = models.ImageField(blank=True) date_published = models.DateTimeField(auto_now_add=True) def __str__(self): return f'Тема {self.subject}' class Meta: verbose_name_plural = 'Вопрос' class Answer(models.Model): id_questions = models.ForeignKey(Quetions,to_field='id',on_delete=models.DO_NOTHING,verbose_name='К какому вопросу',blank=True) user_id = models.ForeignKey. (User,to_field='id',on_delete=models.DO_NOTHING,verbose_name='Пользователь', blank=True) Text = models.TextField(verbose_name='Вопрос') date_published = models.DateTimeField(auto_now_add=True) def __str__(self): return f'Тема {self.id_questions}' class Meta: verbose_name_plural = 'Ответ' Автозаполнение в двух таблицах я сделал так: views.py def Questions(request): if request.method == 'POST': user = request.user form = QuestionsForm(request.POST) if form.is_valid(): instance = form.save(commit=False) instance.User_id = user form.save() return redirect('/') else: return redirect('/') else: form = QuestionsForm() model = Quetions.objects.all() return render(request, 'Questions.html', {'form': form,'model':model}) Не понимаю как сделать автозаполнение поле id_questions в таблице Answer? Заранее СПАСИБО -
Django Rest Swagger Not showing up all the APIs
I am working with Django Rest swagger. But it's not showing up all the APIs. The url paths for /tickets are missing: Even path to /dj-rest-auth/user/ is missing as well: Backend/urls.py from django.contrib import admin from django.urls import path, include from rest_framework_swagger.views import get_swagger_view schema_view = get_swagger_view(title='API') urlpatterns = [ path('admin/', admin.site.urls), #path('api/v1/', include(api_urlpatterns)), #path('dj-rest-auth/', include('dj_rest_auth.urls')), path('dj-rest-auth/', include('dj_rest_auth.urls')), path('dj-rest-auth/registration/', include('dj_rest_auth.registration.urls')), path('api/', include('ticket.urls')), path('swagger/', schema_view) ] Tickets/urls.py from django.urls import path from ticket import views urlpatterns = [ path('tickets/', views.ticket_list), path('tickets/<int:pk>/', views.ticket_detail), ] My directory structure: -
Override dispatch() method in PasswordResetConfirmView
I have written a class that inherits from PasswordResetConfirmView PasswordResetConfirmView can be found here: https://github.com/django/django/blob/7f4fc5cbd4c26e137a1abdd9bd603804ddc0e769/django/contrib/auth/views.py#L260 For what it's worth here is the part of the class that I have written (nothing ground breaking I know!): class PwdResetConfirm(PasswordResetConfirmView): template_name = 'account/password_reset_confirm.html' success_url = reverse_lazy('two_factor:login') form_class = PwdChangeForm What I want to do is change the behaviour of PasswordResetConfirmView dispatch() method so that a message is created if a password reset is unsuccessful, so the lines in PasswordResetConfirmView: # Display the "Password reset unsuccessful" page. return self.render_to_response(self.get_context_data()) would effectively become: messages.success(self.request, _(mark_safe( 'Your password change link appears to be invalid.'))) # Display the "Password reset unsuccessful" page. return self.render_to_response(self.get_context_data()) I am new to overriding classes and as such,I am not even sure where to start. In summary, my question is: How can I add the message to PasswordResetConfirmView class's dispatch() method without overriding the entire method? -
django-activity-stream and django-comments-xtd
On a django project i'm using both django-activity-stream and django-comments-xtd, Is there a way to build a stream of the comments posted via the django-comments-xtd package ?? because obviously I will not modifiy the code of the comment package... to add action in it (see action help in the help) How am I supposed to do so ?? Thanks for your help -
how to join in queryset
I have some problems with QuerySet in Django python. I have 2 tables/models. class PP(models.Model): imei = models.BigIntegerField(primary_key=True) name = models.CharField(max_length = 50) val2 = models.IntegerField(default = 0) def __str__(self): return self.name class Mea(models.Model): imei = models.ForeignKey(PP, on_delete=models.CASCADE) v1 = models.IntegerField(default = 0) v2 = models.IntegerField(default = 0) v3 = models.IntegerField(default = 0) dates = models.DateField(default=datetime.date.today) def __str__(self): return self.imei PP +----+--------+------+ |imei| name | val2 | +----+--------+------+ | 1 | john | 12 | | 2 | adam | 5 | | 3 | alfred | 3 | +----+--------+------+ Mea +----+----+----+-----+---------------------+ |imei| v1 | v2 | v3 | date | +----+----+----+-----+---------------------+ | 1 | 4 | 15 | 18 | 2020-10-16 11:15:53 | | 1 | 2 | 12 | 17 | 2020-10-16 11:22:53 | | 1 | 3 | 13 | 16 | 2020-10-16 11:32:53 | | 2 | 1 | 16 | 15 | 2020-10-16 13:22:53 | | 2 | 3 | 13 | 25 | 2020-10-16 13:42:53 | | 2 | 4 | 12 | 35 | 2020-10-16 14:12:53 | | 3 | 1 | 21 | 12 | 2020-10-16 14:12:53 | | 3 | 2 | 28 | 42 | 2020-10-16 15:12:53 | | 3 … -
Calling value from ajax to Django views
Im confused why it returns None when I print the value that comes from ajax, I used request.POST.get("ajaxvalue") to get the value from ajax requests but it didn't work, can anyone know what's the problem I encountered? it's very helpful for me. views.py @csrf_exempt def updateStatus(request): if request.method=="POST": taskId = request.POST.get('id') source = request.POST.get("sources") target = request.POST.get('targets') print(taskId); print(source); print(target); return JsonResponse({'datas': 'test'}) html ajax $.ajax({ data: { id, 'sources':0, 'targets':1 }, url: "{% url 'updateStatus' %}", type: 'POST', cache: false, contentType: false, processData: false }) .done(function(data){ console.log("success"); }); urls.py urlpatterns = [ path('updateStatus/',views.updateStatus, name='updateStatus'), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)