Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use same serializer class for get and post method in Django 4.2?
I have been trying, but fail miserably, to use only a single serializer class for both post and get api call. I have a team model that has many to many relationship with the project model. I want to only use the id when am doing the post but when doing the GET request am able to view the details of the team team model from django.db import models from django.contrib.auth import get_user_model from . import Project class Team(models.Model): name = models.CharField(max_length=70) description = models.TextField() members = models.ManyToManyField(get_user_model()) projects = models.ManyToManyField(Project, blank=True, related_name='teams_projects') def __str__(self) -> str: return str(self.name) project model from django.db import models class Project(models.Model): PENDING = 'Pending' IN_PROGRESS = 'In Progress' COMPLETED = 'Completed' STATUS_CHOICES = [ (PENDING, 'Pending'), (IN_PROGRESS, 'In Progress'), (COMPLETED, 'Completed'), ] name = models.CharField(max_length=70) description = models.TextField() start_date = models.DateField() end_date = models.DateField() teams = models.ManyToManyField('Team', related_name='team_projects') status = models.CharField(max_length=20, choices=STATUS_CHOICES, default=PENDING) def __str__(self) -> str: return str(self.name) I have tried to use 'depth' but now am required provide team information instead of only id when doing the post. POST request body { "name": "string", "description": "string", "members": [ 0 ], "projects": [ { "name": "string", "description": "string", "start_date": "2023-09-29", "end_date": "2023-09-29", "status": … -
Digitalocean build stuck
I want to run a Python Django app on Digital Ocean and use this tutorial. It worked in the spring, but now the build stops (stuck) in the app upload stage. Any ideas? -
Access many-to-many field in Django template
I have a model Post and a model User, any User can leave one like to a post. class User(AbstractUser): pass class Post(models.Model): liked = models.ManyToManyField('User', blank=True, related_name='liked_post') How can I check in the django template if the current user liked the specific post or not? Previously I just wrote {% if user in post.liked.all %} without thinking, and now I understand that this must be a terrible implementation, because if the post has like 5000 likes, then django will have to iterate through a huge list. I could probably make an additional dictionary in the view (where the key is the ID of the post and value is a result of additional query), then pass this dictionary in the context, but there might be a better implementation. Can I just check in the template if user liked the post efficiently? -
How to terminate active Celery tasks?
In my Django project, I am using Celery, and I have a list of all currently active tasks like this: active_tasks = i.active() Now, I want to terminate these tasks. They are running on a Celery worker, and I'm wondering how to achieve this. Can someone please provide guidance on how to stop these active tasks using Celery's API? I already use revoke method but it does not work, here is a pseudo-code snippet: for task_id in active_task: async_result = AsyncResult(task_id) async_result.revoke(terminate=True) -
Outputting validation error correctly : Django
The below code validates the email address provided and shows up a message if the email address is invalid. from django.core.validators import validate_email from django.core.exceptions import ValidationError is_valid = validate_email(user.email) try: if is_valid == True: password1 = request.POST.get('txtPassword') password2 = request.POST.get('txtConfPassword') except ValidationError: messages.error(request, "Email address is invalid...") I want this validation error displayed in the form and the user needs to stay in the form, but unfortunately it gets redirected to the errro page ValidationError at /register/ ['Enter a valid email address.'] Request Method: POST Request URL: http://127.0.0.1:8000/register/ Django Version: 4.2.5 Exception Type: ValidationError Exception Value: ['Enter a valid email address.'] Exception Location: E:\theparams\theparamsenv\Lib\site-packages\django\core\validators.py, line 210, in __call__ Raised during: theparams.views.registerPage Python Executable: E:\theparams\theparamsenv\Scripts\python.exe Python Version: 3.11.4 Python Path: ['E:\\theparams', 'C:\\Users\\Win\\AppData\\Local\\Programs\\Python\\Python311\\python311.zip', 'C:\\Users\\Win\\AppData\\Local\\Programs\\Python\\Python311\\DLLs', 'C:\\Users\\Win\\AppData\\Local\\Programs\\Python\\Python311\\Lib', 'C:\\Users\\Win\\AppData\\Local\\Programs\\Python\\Python311', 'E:\\theparams\\theparamsenv', 'E:\\theparams\\theparamsenv\\Lib\\site-packages'] Server time: Fri, 29 Sep 2023 11:10:10 +0000 -
Django CSP unable to make it work with Bootstrap Icons
setings.py: CSP_DEFAULT_SRC = ("'self'",) CSP_INCLUDE_NONCE_IN = ('script-src', ) CSP_STYLE_SRC = ("'self'", "rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65", "https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css",) CSP_SCRIPT_SRC = ("'self'", "'unsafe-inline'", "https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js") html: <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-icons/1.10.2/font/bootstrap-icons.min.css" integrity="sha512-YFENbnqHbCRmJt5d+9lHimyEMt8LKSNTMLSaHjvsclnZGICeY/0KYEeiHwD1Ux4Tcao0h60tdcMv+0GljvWyHg==" crossorigin="anonymous"> Browser Console: Content-Security-Policy: The page’s settings blocked the loading of a resource at https://cdnjs.cloudflare.com/ajax/libs/bootstrap-icons/1.10.2/font/bootstrap-icons.min.css (“style-src”). I have already tried to add them to CSP_STYLE_SRC, CSP_IMG_SRC and to CSP_DEFAULT_SRC. What am i missing? -
DATETIME_FORMAT setting in Django causing delete action in Django admin to throw ValidationError
I have an issue where if I use the default value for DATETIME_FORMAT, when I select a row/rows in the django admin and select the delete action, the timestamp causes a validation error. If I do DATETIME_FORMAT = (( 'Y-m-d H:i:sO' )), I can remove the error. I have the feeling I am doing something seriously wrong when I have to change a default value like this. I looked through the timezone documentation but wasn't able to explain to myself why I needed to change the default in this way. An explanation or reference to the documentation that explains this behavior would be greatly appreciated. -
Stripe payment tunnel with different subscriptions
I work with django/python and stripe API pip package I am looking to create a stripe payment tunnel allowing me to bill a basket in one go that can contain : Single Purchase items One or more subscriptions which may have a different price and frequency The customer must be able to cancel one subscription without canceling the other which would be subscribed at the same time. I'm having trouble understanding the payment tunnel, which method I should use in the API I need to be guided through the broad outlines of the process For now I have: retrieved or created the client retrieved or created the article created a unique price (price_id) Checkout gave bad results because there cannot be several subscription type items with different frequency in checkout -
when refreshing the page getting previous post requsts value
enter a value in input and submitting the form getting error message wich i setted in form validation.but when refresh getting previous data which entered in same input. view.py: from django.forms import ValidationError from . import forms from django.shortcuts import render,redirect from django.contrib.auth import authenticate,login,logout from django.core import validators def user_login(request): if request.method == 'POST': form = forms.LoginForm(request.POST.dict()) print(request.POST) if form.is_valid(): # Handle valid form submission username=form.cleaned_data['name'] password=form.cleaned_data['password'] user=authenticate(username=username,password=password) if user is not None: login(request,user) return redirect(home) elif user is None : raise ValidationError('required') else: form = forms.LoginForm() return render(request, "login.html", context={'form': form}) def home(request): if request.user.is_authenticated: return render(request,"home.html") return redirect(user_login) def user_logout(request): if request.user.is_authenticated and request.META.get('HTTP_REFERER') is not None: logout(request) return redirect(home) login.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>login</title> {% load bootstrap5 %} {% bootstrap_css %} {% bootstrap_javascript %} </head> <body> <div class=" w-50 container " style="border-radius: 20px; background-color: darkgrey;"> <h1 class="mt-5 pt-5 mb-0 text-center ">login</h1> <div class="h-100 d-flex align-items-center justify-content-center "> <form class="w-50 m-5 container" method="post"> {% csrf_token %} {{ form.name.label_tag }} {{ form.name }} <div class="error-message" style="color:red">{{ form.name.errors }}</div> {{ form.password.label_tag }} {{ form.password }} <div class="error-message">{{ form.password.errors }}</div> <button type="submit" class="btn btn-primary mt-1">Login</button> </form> <!-- <form class="w-50 m-5 container" method="post" … -
Get user information in the Django template (admin)
I am trying to access information related to the present logged-in user in the Django admin custom template change_list_results.html for a specific model. But I am not able to access any user information in the template. We are using Django 4.0.4. I am over-riding an admin template (change_list_results.html) and trying to get user information in the template(either username or email). I have tried to use the below variables (suggested in some other threads), but none of them work. {{ user }} {{ user.username }} {{ request.user }} {{ request.user.username }} Below is how the template context_processors being set in the settings.py. Some people suggested that django.contrib.auth.context_processors.auth in this should give access to user object. But I do not get the user object in template: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] I tried to add a context variable by adding below block to the model, but even this did not work. Referencing {{username}} after this just results in empty value def changelist_view(self, request): return super().changelist_view(request, extra_context={"username": request.user.username}) Please help with how I can get information related to user within the template. Thanks! -
django.db.utils.InterfaceError: connection already closed on unit tests with postgres
My unit tests are working perfectly on sqlite but I'm trying to make them work on postgres. I'm using python 3.6 and Django 2.2.28. Unit test fails when Django tries to auth the user: .tox/commonenv/lib/python3.6/site-packages/django/http/response.py:169: in set_cookie self.cookies[key] = value /usr/local/lib/python3.6/http/cookies.py:518: in __setitem__ if isinstance(value, Morsel): .tox/commonenv/lib/python3.6/site-packages/django/utils/functional.py:256: in inner self._setup() .tox/commonenv/lib/python3.6/site-packages/django/utils/functional.py:392: in _setup self._wrapped = self._setupfunc() .tox/commonenv/lib/python3.6/site-packages/django/contrib/auth/middleware.py:24: in <lambda> request.user = SimpleLazyObject(lambda: get_user(request)) .tox/commonenv/lib/python3.6/site-packages/django/contrib/auth/middleware.py:12: in get_user request._cached_user = auth.get_user(request) .tox/commonenv/lib/python3.6/site-packages/django/contrib/auth/__init__.py:189: in get_user user = backend.get_user(user_id) .tox/commonenv/lib/python3.6/site-packages/django/contrib/auth/backends.py:102: in get_user user = UserModel._default_manager.get(pk=user_id) .tox/commonenv/lib/python3.6/site-packages/django/db/models/manager.py:82: in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) .tox/commonenv/lib/python3.6/site-packages/django/db/models/query.py:402: in get num = len(clone) .tox/commonenv/lib/python3.6/site-packages/django/db/models/query.py:256: in __len__ self._fetch_all() .tox/commonenv/lib/python3.6/site-packages/django/db/models/query.py:1242: in _fetch_all self._result_cache = list(self._iterable_class(self)) .tox/commonenv/lib/python3.6/site-packages/django/db/models/query.py:55: in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) .tox/commonenv/lib/python3.6/site-packages/django/db/models/sql/compiler.py:1140: in execute_sql cursor = self.connection.cursor() .tox/commonenv/lib/python3.6/site-packages/django/db/backends/base/base.py:256: in cursor return self._cursor() .tox/commonenv/lib/python3.6/site-packages/django/db/backends/base/base.py:235: in _cursor return self._prepare_cursor(self.create_cursor(name)) .tox/commonenv/lib/python3.6/site-packages/django/db/utils.py:89: in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value .tox/commonenv/lib/python3.6/site-packages/django/db/backends/base/base.py:235: in _cursor return self._prepare_cursor(self.create_cursor(name)) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ … -
Not able to validate password inside views.py django
I have my own HTML form and I am using AbstractUser to create my own model, the problem that I am facing is when I try to register a new user I need to check whether the password and confirm password field matches. If it does not match, then I need to throw an error message. I have written this below logic in "views.py", the problem is even if the password does not match a new user is getting created in the backend. I am not sure what I am doing wrong here. def registerPage(request): #form = UserCreationForm() user = User() if request.method == "POST": user.first_name = request.POST.get('txtFName') user.last_name = request.POST.get('txtFName') user.username = request.POST.get('txtUserName').lower() user.email = request.POST.get('txtEmail').lower() password1 = request.POST.get('txtPassword') password2 = request.POST.get('txtConfPassword') if password1 == password2: user.set_password(password2) else: messages.error(request, "Password and Confirm password do not match. Try again") user.is_superuser = False user.save() login(request, user) return redirect('home') return render(request,'login_register.html') -
Bulk create many-to-many objets to self
Having model class MyTable(Model): close = ManyToManyField("MyTable") How to bulk create objects to this relation? With tables not related to itself, one could use db_payload =[MyTable.close.throught(tablea_id=x, tableb_id=y) for x,y in some_obj_list] MyTable.close.through.objects.bulk_create(db_payload) What would be the keyword arguments in case where relation is to the table itself? -
Multi peer video call using webrtc and django channel(websockets)
I am trying to build a Multi user video call using webrtc and django channel in a chat room , similar to what discord does ,in that i have successfully implemented it for 2 users . So when user 1(host) starts the call , an "offer" along with "ice candidates " gets sent to connected users in the room . Now i have a "Join Call " button for processing the data from host and sending "answer" and "ice-candidates" back , this is working fine for 2 users , but now in the 3rd user , that user first gets host's offer and without it processing it , the 3rd user gets user 2' answer . So when user 3 clicks on join call , the 3rd user can only see his local stream , and the ongoing call between 1 and 2 is happening without any change . So basically 3rd user is unable to join the ongoing call . How can i resolve this issue at hand ? I am using webrtc for peer connections and offer/answers And i am using Django channels'websocket for signalling -
How to Join (NOT COMBINE) two more django querysets?
I’m new to Django framework, may be this problem seem to be fun to some experienced developers here. So, I have a django model: STATUS_CHOICES = ( (‘CL’, ‘CLOSED’), (‘FR’, ‘FORWARDED’), (‘PE’), ) class References(modles.Model): ref_no = models.CharField(max_length=) date_received = models.DateField() status = models.CharField(max_length=2, choices=STATUS_CHOICES) I am required to query the data in this format:- Year Month #Total Ref. #CLOSED #FORWARDED #PENDING 2023 Jan 3 1 1 1 2023 Feb 1 0 1 0 2023 Mar 1 0 0 1 Sample data: Ref_No (unique) Date_Recieved Status ABC-123 01-Jan-2023 CLOSED BCD-234 01-Feb-2023 FORWARDED DEF-567 01-Jan-2023 PENDING ABC-891 01-Jan-2023 CLOSED DEF-967 01-Mar-2023 PENDING I created three different querysets but don’t know how to join them to produce above results: - # TOTAL q_total = References.objects.all() \ .values('date_received__year', 'date_received__month') \ .annotate(dcount=Count(‘ref_no’)) \ .order_by('date_received__year', ‘date_received__month') # CLOSED q_total = References.objects.filter(Q(status__iexact='CL') \ .values('date_received__year', 'date_received__month') \ .annotate(dcount=Count(‘ref_no’)) \ .order_by('date_received__year', ‘date_received__month') # FORWARDED q_total = References.objects.filter(Q(status__iexact='FR') \ .values('date_received__year', 'date_received__month') \ .annotate(dcount=Count(‘ref_no’)) \ .order_by('date_received__year', ‘date_received__month') # PENDING q_total = References.objects.filter(Q(status__iexact='PE') \ .values('date_received__year', 'date_received__month') \ .annotate(dcount=Count(‘ref_no’)) \ .order_by('date_received__year', ‘date_received__month') Any help would be appreciated. The above is just a small sample problem. -
You cannot access body after reading from request's data stream : Swagger integration with django
Not able to access request.body after adding extend_schema. Where my message are already consumed i am using standard middleware only that comes with django setup from rest_framework import decorators, serializers from drf_spectacular.utils import extend_schema, OpenApiParameter, inline_serializer from drf_spectacular.types import OpenApiTypes from django.views.decorators.csrf import csrf_exempt @extend_schema( request=inline_serializer( name="MemberSerializer", fields={ "loan_ids": serializers.ListField(), }, ), responses=OpenApiTypes.OBJECT, methods=['POST'], ) @decorators.api_view(http_method_names=['post']) @csrf_exempt def post_member(request): request_body = json.loads(request.body.decode('utf-8')) return JsonResponse({'success': True, 'request': request_body}, status=200) Middlewares : "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", i don't want to use request.data to fetch the input request data, Wanted to know where i have consumed the request.body the first time -
Django testing disable app and middle ware to test multiple databases setup with only one testing database
I am using multiple databases where in a special case I am streaming data into a warehouse (by using signals). However, for testing the business logic I don't want to stream warehouse data so I want to disable this app and middleware. But something is wrong since the test still requires multiple database settings: @override_settings(REST_FRAMEWORK={"PAGE_SIZE": 2}) @modify_settings(MIDDLEWARE={'remove': ['dwhstreaming.middleware.LoggingStackMiddleware']}, INSTALLED_APPS={'remove': ['dwhstreaming']}) class TestAPI(TokenAuthenticatedTestAPI): # Test works fine if I add these: # multi_db = True # databases = {'default', 'dwh-stream'} def test_create_client(self): client = deepcopy(SAMPLE_CLIENT) # do something ... Fails with: Database queries to 'dwh-stream' are not allowed in this test -
Issue with passing Django URL parameters while dynamically changing the inner HTML of a Django template using Javascript
I am trying to dynamically change the innerHTML of a Django template using Javascript. There are some anchor tags inside the HTML content. Their href contains Django URL with some parameters. There is some issue with it, but can't figure it out. $.ajax({ url: "{%url 'fact:datalist' %}", type: 'POST', headers: { "X-CSRFToken": token, }, dataType: 'json', data: { csrfmiddlewaretoken: token, seldata: selectedDate, } }).done(function (data) { const pdata = JSON.parse(data) pdata.forEach((key, index) => { const val = key.fields; console.log(val) const nid = val.result_id; trdata = `<tr> <td>${index}</td> <td style="display: none;"> ${nid} </td> <td><a href="{%url 'fact:entry_form' id=${nid} %}"> ${val.pdtcode} </a></td> <td> ${val.process_code} </td> <td> ${val.prev_count} </td> <td> ${val.ok_count} </td> <td> ${val.ng_count} `; if (val.ng_count != 0) { trdata = `<br><a href="{%url 'fact:editform' id=${nid} %}"> Edit </a>`; } trdata = `</td> <td> ${val.unattended_count}`; if (val.unattended_count != 0) { trdata = `<br><a href="{%url 'fact:checkform' id=${nid} %}"> Check </a>`; } trdata = `</td> </tr>`; $('.data_view>tbody').html(trdata) }); }) } The issue exists at the id=${nid} part of every URL. Need some advice to tackle this issue. Thanks in advance -
"ModuleNotFoundError: No module named" error for a local module in django
I have a local custom module that I want to use in my webservice but I got "ModuleNotFoundError: No module named" error. even when my editor can detect the module. At firs I think it was because of crontab that I'm using but even when I change ot to somthing else I still got this error. Even I changed the structure of my project and I still getting this error -
form validation error message not displaying
ther was no displaying error message in website and ther was no any elements for view errors view.py: from . import forms from django.shortcuts import render,redirect from django.contrib.auth import authenticate,login,logout from django.core import validators def user_login(request): form=forms.LoginForm() if request.POST: form=forms.LoginForm(request) # if request.user.is_authenticated: # return redirect('home') return render(request,"login.html",context={'form':form,'message':''}) def home(request): if request.user.is_authenticated: return render(request,"home.html") return redirect(user_login) def user_logout(request): if request.user.is_authenticated and request.META.get('HTTP_REFERER') is not None: logout(request) return redirect(home) forms.py: from django import forms from django.core import validators class LoginForm(forms.Form): name= forms.CharField(validators=[validators.MinLengthValidator(4,"errorororokjjkkj hjkhjkjhk hkhkh j")],widget=forms.TextInput(attrs = {'class':"form-control mb-3",'placeholder':"Username"})) password=forms.CharField(widget=forms.PasswordInput(attrs = {'class':"form-control mb-3",'placeholder':"password"})) login.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>login</title> {% load bootstrap5 %} {% bootstrap_css %} {% bootstrap_javascript %} </head> <body> <div class=" w-50 container " style="border-radius: 20px; background-color: darkgrey;"> <h1 class="mt-5 pt-5 mb-0 text-center ">login</h1> <div class="h-100 d-flex align-items-center justify-content-center "> <form class="w-50 m-5 container" method="post" > {%csrf_token%} {{form}} {{message}} <button type="submit" class="btn btn-primary mt-1" onclick="">login</button> </form> <!-- <form class="w-50 m-5 container" method="post" enctype="multipart/form-data" > {%csrf_token%} <label for="exampleFormControlSelect1">Username</label> <input type="text" class="form-control mb-3" placeholder="Username" name="username" required> <p>{{message}}</p> <label for="password">password</label> <input class="form-control mb-3" type="password" name="password" placeholder="password" required></input> <button type="submit" class="btn btn-primary mt-1" onclick="">login</button> </form> --> </div> </div> </div> </body> </html> i want display error without using … -
I have a field with current/permanent_address and I need to use this field with forward slash in my serializer
this is my serializer and I am not able to declare fields in my serilizer with forward slash "address": { "current/permenantAddress": { "PERM_LINE1": "delhi vasant vihar", "PERM_LINE2": "vasant vihar", }, "correspondence/localAddress": { "CORRES_LINE1": "", } } } -
100% CPU Utilization on my VPS - Django app gunicorn
I have a VPS running Nginx, Django, Postgres and a Golang microservice in a Docker compose environment and recently I've noticed it's consistently hitting 100% CPU utilization and not working anymore. I suspect this may be due to a DDoS attack or weird gunicorn behavior. VPS OS: Ubuntu 22.04.2 LTS Observations: The high CPU usage started around yesterday (24hrs ago). Steps Taken: Setup and config ufw, and a digitalocean firewall. NGINX Logs ... 89.44.9.51 - - [29/Sep/2023:05:09:58 +0000] "OPTIONS /webclient/api/MyPhone/session HTTP/1.1" 444 0 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) 3CXDesktopApp/18.13.959 Chrome/112.0.5615.165 Electron/24.3.0 Safari/537.36" "-" 89.44.9.51 - - [29/Sep/2023:05:10:01 +0000] "GET /provisioning/5lbr5h6kse0q/TcxProvFiles/3cxProv_YU8SR32OGF200.xml HTTP/1.1" 444 0 "-" "electron-fetch/1.0 electron (+https://github.com/arantes555/electron-fetch)" "-" 89.44.9.51 - - [29/Sep/2023:05:10:07 +0000] "GET /provisioning/5lbr5h6kse0q/TcxProvFiles/3cxProv_YU8SR32OGF200.xml HTTP/1.1" 444 0 "-" "electron-fetch/1.0 electron (+https://github.com/arantes555/electron-fetch)" "-" 89.44.9.51 - - [29/Sep/2023:05:10:12 +0000] "GET /provisioning/5lbr5h6kse0q/TcxProvFiles/3cxProv_YU8SR32OGF200.xml HTTP/1.1" 444 0 "-" "electron-fetch/1.0 electron (+https://github.com/arantes555/electron-fetch)" "-" 89.44.9.51 - - [29/Sep/2023:05:10:17 +0000] "GET /provisioning/5lbr5h6kse0q/TcxProvFiles/3cxProv_YU8SR32OGF200.xml HTTP/1.1" 444 0 "-" "electron-fetch/1.0 electron (+https://github.com/arantes555/electron-fetch)" "-" 89.44.9.51 - - [29/Sep/2023:05:10:22 +0000] "GET /provisioning/5lbr5h6kse0q/TcxProvFiles/3cxProv_YU8SR32OGF200.xml HTTP/1.1" 444 0 "-" "electron-fetch/1.0 electron (+https://github.com/arantes555/electron-fetch)" "-" 89.44.9.51 - - [29/Sep/2023:05:10:27 +0000] "GET /provisioning/5lbr5h6kse0q/TcxProvFiles/3cxProv_YU8SR32OGF200.xml HTTP/1.1" 444 0 "-" "electron-fetch/1.0 electron (+https://github.com/arantes555/electron-fetch)" "-" 89.44.9.51 - - [29/Sep/2023:05:10:32 +0000] "GET /provisioning/5lbr5h6kse0q/TcxProvFiles/3cxProv_YU8SR32OGF200.xml HTTP/1.1" 444 0 "-" … -
insert the POST list to the db in Django?
We encountered a problem. Can you help? I am sending a list via POST. lists will be recorded in the table in two fields. Send List in HTML. As follows, validate result from html. Your list data are: ('csrfmiddlewaretoken', ['..']) ('x1', ['1', 'Закройный']) ('x2', ['2', 'Закройный']) ('x3', ['3', 'Закройный']) Models.py from django.db import models class Testmodel(models.Model): ws1 = models.CharField(max_length=100, blank=True) ws2 = models.CharField(max_length=100, blank=True) input.html <form action="../validate" method="POST"> {% csrf_token %} {% for work_stations in ws %} {% if work_stations.is_active %} <input name="x{{ work_stations.id }}" value="{{ work_stations.id }}"> <input name="x{{ work_stations.id }}" value="{{ work_stations.category }}"> {% endif %} {% endfor %} <input type="submit" > </form> views.py from django.shortcuts import render from .models import Testmodel def createpost(request): if request.method == 'POST': list_data = (list(request.POST.lists())) #Here I need to save list_data to the database. The following code does not work. mylist = list_data Testmodel.objects.bulk_create([Testmodel(**{ 'ws1' : x[0], 'ws2' : x[1]}) for x in mylist]) -
Django, MySQL tests create all tables, but why is each table empty?
Problem Statement: When I use any test case that tries a db lookup I get a typical db error like "matching query does not exist." I cannot figure out why test db creation creates the tables, but fails to put the data into the tables. Using MySQL db in development works fine. So Far: Performed significant amounts of searching for similar issues posted by others, but failed to find any I used --keepdb and found that all tables successfully create, however, they are all empty; even tables like auth_user. Work around: I can manually add data to the test tables and reach a successful test case with a db query (yay!), however, it is a super pain and not easily repeatable (or sustainable). =========================== Notes: Migrations are regularly deleted from django_migrations table and the migrations directory with subsequent make and fake. The standalone migration file; 0001_initial.py looks good. Using typical database settings, no test db defined, no mirrors. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': '***', 'USER': '***', 'PASSWORD': '***', 'HOST': 'localhost', 'PORT': '3306', } } -
Manually validating csrftoken in Django
<script> const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value; let submitFormData = () => { const formData = new FormData(); // Add form data // This line may not be required as the header contains it formData.append('csrftoken', csrftoken); const request = new Request( URL, {headers: {'X-CSRFToken': csrftoken}} ); return fetch(request, { method: 'POST', mode: 'same-origin', body: formData }) .then(response => response.json()) .then(response => { data = response['time']; return data; }); } </script> How do I validate csrftoken on the server side in Django / python ? I am not using DRF here. Django 4.2