Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to add product in cart in Django
i am trying to add product to cart by getting its id this is the path enter image description here this is views.py view.py enter image description here '''please suggest me a way to get product by their id and to add them in cart ''' -
Bootstrap-table data clears on search, filter or paginate after Ajax call
In my Django template I have a bootstrap-table (version 1.21.2) (https://bootstrap-table.com/) which is filled with multiple customers, whenever a customer is clicked, it will create a popup with a bootstrap-table in which all data for that customer is displayed using Ajax. The problem, is that, whenever I try to search, filter or paginate, it clears the entire table. I think this is because bootstrap-table clears the entire table, and then refills it with whatever you're trying to search. Here is my code: Ajax: function get_customer_leadtime(customerCode, customerName, warehouse) { $.ajax({ type:"GET", url: "{% url 'get_customer_leadtime' %}", data:{ "customerCode": customerCode, "customerName": customerName, "warehouse": warehouse }, success: function (response) { var title = customerName var table = $("#customerLeadtimeTable tbody"); document.getElementById("customerLeadtimeLabel").innerHTML = title; table.empty() $.each(response, function(idx, customerInfo){ $.each(customerInfo, function(_, details){ table.append( "<tr><td>"+details.Article +"</td><td>"+details.Leadtime +"</td></tr>" ); }); }); $("#customerLeadtimeModal").modal('show'); }, error: function (response) { console.log(response) } }); } Ajax GET example URL: GET /get/ajax/leadtime?customerCode=00000&customerName=SomeCustomer%20BV&warehouse=SomeLocation HTTP/1.1" 200 9216 HTML: <table class="table table-hover table-sm" id="customerLeadtimeTable" data-toggle="table" data-show-multi-sort="true" data-show-search-clear-button="true" data-show-export="true" data-search="true" data-filter-control-multiple-search="true" data-filter-control="true" data-search-align="left" data-pagination="true" data-side-pagination="client" data-page-size="10" data-page-list="[10, 25, 50, ALL]" data-click-to-select="true" data-show-toggle="true" data-show-columns="true" > <thead> <tr> <th scope="col" data-field="Article" data-width="50" data-width-unit="%">Article</th> <th scope="col" data-field="Leadtime" data-width="50" data-width-unit="%">Average leadtime</th> </tr> </thead> <tbody> <tr> </tr> </tbody> </table> Image of the … -
Add a OnetoOne field in an already populated Django ORM
I have this customer model where I want to introduce a user field where the user field is user = models.OneToOneField(User, on_delete=models.CASCADE) but there are already some objects in this model so if i create this one to one field then it would ask me for a default value for those objects but I cannot pass default values because it'll clash with the logic. Old model: class Customer(models.Model): first_name = models.CharField(max_length=50, default=0) last_name = models.CharField(max_length=50, default=0) customer_display_name = models.CharField(max_length=50, default=0) customer_name = models.CharField(max_length=50, default=0) customer_phone = models.CharField(max_length=50, default=0) customer_website = models.CharField(max_length=50, default=0) customer_email = models.EmailField(max_length=250, default=0, blank=True, null=True) shipping_address = models.ManyToManyField(CustomerShippingAddress) billing_address = models.ManyToManyField(CustomerBillingAddress) active = models.BooleanField(default=True) remarks = models.CharField(max_length=500, default=0, blank=True, null=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) New model: class Customer(models.Model): first_name = models.CharField(max_length=50, default=0) last_name = models.CharField(max_length=50, default=0) customer_display_name = models.CharField(max_length=50, default=0) customer_name = models.CharField(max_length=50, default=0) customer_phone = models.CharField(max_length=50, default=0) customer_website = models.CharField(max_length=50, default=0) customer_email = models.EmailField(max_length=250, default=0, blank=True, null=True) shipping_address = models.ManyToManyField(CustomerShippingAddress) billing_address = models.ManyToManyField(CustomerBillingAddress) active = models.BooleanField(default=True) remarks = models.CharField(max_length=500, default=0, blank=True, null=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) #Change1 user = models.OneToOneField(User, on_delete=models.CASCADE) #Change2 company = models.ForeignKey(Company, on_delete=models.CASCADE) #Change3 Reason owner - to track who created this Customer user - to link the Customer to User model company … -
Django sending emails with link
I have an email verification while registering, and the verify link must in the form of a hyperlink. from django.core.mail import send_mail from django.conf import settings def send_email_verification_mail(email, first_name, verify_link, exp): html = """ <a href="{link}">Click to verify</a> """ html.format(link=verify_link) subject = 'Your accounts need to be verified' message = f'Hi {first_name.capitalize()},\n\nClick on the link to verify your account \n \n{html}\n \nThis link will expire in {exp}' email_from = settings.EMAIL_HOST_USER recipient_list = [email] send_mail(subject, message, email_from, recipient_list) return True This is the what I'm getting -
How can I integrate my trained yolov5 model with a Django webapp for real-time object detection?
Im looking for a way to use my trained yolov5 model for real-time object detection on a Django webapp I tried saving the model in torchscript format and loaded the model in a function created in views.py. But when I run py manage.py runserver and try to load the webapp in my browser, my laptop camera seems to be on verge of opening but I end up having an error saying : RuntimeError: The size of tensor a (64) must match the size of tensor b (40) at non-singleton dimension 3 -
Hide and Show button inside a for-loop of template in Alpine.js and Django
Hide and Show button inside a for-loop of template in Alpine.js and Django. conversion of django if else condition template to Alpine.js, How do we convert this code inside a for-loop condition on template using Alpine.js {% if employee.allow_programme_membership_expiry %} <a href="{% url 'buyer:programme-membership-expiry' employee.buyer_id employee.id %}"> {% svg_icon "Change-Expiry" "w-6 h-6 dui-stroke-primary" None "Change Expiry" %} </a> {% endif %} -
How to test async django rest framework
I have a problem with testing async mode in the django rest framework using the adrf library. I created a django project with the view: from rest_framework.decorators import api_view as sync_api_view @sync_api_view(['GET']) def my_not_async_view(request): print('before block endpoint') time.sleep(15) return Response({"message": "my_async_view"}) and I run this code with the uvicorn: uvicorn async_django.asgi:application --workers=1 and test with the curl for x in `seq 1 3`; do time curl http://localhost:8000/async-test/not-async & done; echo Starting And I expect console log result to be (#1): before block endpoint and after 15 sec another before block endpoint but actual result is (#2): before block endpoint before block endpoint # runs in another thread before block endpoint # runs in another thread Why I want result to be (#1) ? Because I want to test async mode and be sure that async mode handling my request, not a thread/instance of the project: import asyncio from adrf.decorators import api_view @api_view(['GET']) async def get_async_response(request): print("async code is running") await asyncio.sleep(10) return Response({"message": "async_result"}) So my logic is when I send a request to my_not_async_view I shouldn't see before block endpoint after 1 call until it gives a response, because it should block my project, but when I send a … -
Why is my JS scroll animation not working in my Django template?
I am trying to do a scroll animation with js in django template that start counting when scrolling down and its not working this is my html <section class="numc"> <div class="nums"> <div class="num" data-goal="50">0</div> <div class="num" data-goal="60">0</div> <div class="num" data-goal="100">0</div> </div> </section> <script src="{% static 'javascript/js.js' %}"></script> and this is js code let nums = document.querySelectorAll(".nums .num"); let section = document.querySelector(".numc"); window.onscroll = function () { if (window.scrollY >= section.offsetTop) { nums.forEach((num) => startCount(num)); } }; function startCount(el) { let goal = el.dataset.goal; let count = setInterval(() => { el.textcontent++; if (el.textcontent == goal) { clearInterval(count); } }, 10); } -
I am getting same error everytime. Can you please guide me what to do
while True: user_type = input("Select user type from the list of users: Admin/Banker/Customer (or 'q' to quit): ") if user_type.lower() == "admin": login = bank_app.display_welcome_screen() from admin import admin_main admin_main() this is a part of my code which is getting error. the error is given below. Select user type from the list of users: Admin/Banker/Customer (or 'q' to quit): admin Traceback (most recent call last): File "C:\Users\DELL\Desktop\python projects\Bank System\main.py", line 153, in main() File "C:\Users\DELL\Desktop\python projects\Bank System\main.py", line 109, in main login = bank_app.display_welcome_screen() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: BankApp.display_welcome_screen() takes 0 positional arguments but 1 was given PS C:\Users\DELL\Desktop\python projects\Bank System> i have made a python banking app system. there are total of 4 files in my project. one is main.py file, second one is admin.py, third one is banker.py and the last one is customer.py. now when i run the main file using command python main.py, my output on the terminal is PS C:\Users\DELL\Desktop\python projects\Bank System> python main.py Account created successfully Account created successfully Deposited successfully Withdrawn successfully Transferred successfully 800.0 Do you want to continue? (y/n): y Account created successfully Account created successfully Deposited successfully Withdrawn successfully Transferred successfully 800.0 Do you want to continue? (y/n): n PS C:\Users\DELL\Desktop\python projects\Bank … -
Why does the first django migration on an empty project take so much time?
The first django migration on an empty project takes a lot of time In my server, I wanted to test the installation of django. But after creating the project, I notice that the migration takes a lot of time. I have searched the web but I only find examples of projects that have already modified the code generated by django-admin. Here are the commands I did: django-admin startproject test_dj cd test_dj ./manage.py migrate # This take long time Can anyone help me? -
Column not Exist error although column is in db django
The I m running into an error that column exists. I checked the DB and found that column is present in the database Django.db.utils.ProgrammingError: column "topic" of relation "post_post" does not exist LINE 1: ... "id", "topic... I have tried the following : Post._meta.get_field('topic') got django.db.models.fields.CharField: topic So the field exists too. -
How do I reference multiple schema files in Graphene Django project settings for access in graphql?
I got a Django project with two apps. The project uses graphene-django. Each of the apps got their own schema.py file. How do i reference both the schema files in settings.py in the project folder so that I can access all the schema's in graphql? I have tried: GRAPHENE = { "SCHEMA": "blog.schema.schema", "newsletter.schema.schema", GRAPHENE = { "SCHEMA":[ "blog.schema.schema", "newsletter.schema.schema", ], ...and other combinations which I can't remember, but they all either lead to errors or to just the last schema in the list to work. -
How can I resolve the 'ModuleNotFoundError' for 'Authentication.urls' when running a Django server in VS Code?
Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last):`` File "C:\Users\vasav\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 1038, in _bootstrap_inner self.run() File "C:\Users\vasav\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 975, in run self._target(*self._args, **self._kwargs) File "C:\Users\vasav\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\vasav\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\commands\runserver.py", line 133, in inner_run self.check(display_num_errors=True) File "C:\Users\vasav\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\base.py", line 485, in check all_issues = checks.run_checks( ^^^^^^^^^^^^^^^^^^ File "C:\Users\vasav\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\checks\registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\vasav\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\checks\urls.py", line 42, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\vasav\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\checks\urls.py", line 61, in load_all_namespaces url_patterns = getattr(resolver, "url_patterns", []) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\vasav\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\functional.py", line 57, in __get__ res = instance.__dict__[self.name] = self.func(instance) ^^^^^^^^^^^^^^^^^^^ File "C:\Users\vasav\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\urls\resolvers.py", line 715, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) ^^^^^^^^^^^^^^^^^^^ File "C:\Users\vasav\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\functional.py", line 57, in __get__ res = instance.__dict__[self.name] = self.func(instance) ^^^^^^^^^^^^^^^^^^^ File "C:\Users\vasav\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\urls\resolvers.py", line 708, in urlconf_module return import_module(self.urlconf_name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\vasav\AppData\Local\Programs\Python\Python311\Lib\importlib_init.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 690, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 940, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "C:\LOGIN PAGE\lakshman\urls.py", line 23, in <module> path('',include('Authentication.urls')) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\vasav\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\urls\conf.py", … -
Time conflicts and empty messages - Realtime chat application
community. Problem: I'm working on a real-time django chat application. When user messages it shows the right current time but, it's gets changed to a different time on refershing the page. Here are the snaps for your reference: Real time chatting After refreshing the page - Note-time has been changed on refreshing and some empty messages are coming as well What i want is .... as a real-time chat application the time and empty message should not show on refreshing the page. Here is the code that i've implemented: message model class Message(models.Model): room = models.ForeignKey(Room, related_name='messages', on_delete=models.CASCADE) user = models.ForeignKey(User, related_name='messages', on_delete=models.CASCADE) content = models.TextField() date_added = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('date_added',) Java Script <script> const roomName = JSON.parse(document.getElementById('json-roomname').textContent); const userName = JSON.parse(document.getElementById('json-username').textContent); const chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/' + roomName + '/' ); chatSocket.onclose = function(e) { console.log('onclose') } chatSocket.onmessage = function(e) { const data = JSON.parse(e.data); if (data.message) { const currentTime = new Date().toLocaleTimeString('en-US', { hour: 'numeric', minute: 'numeric', hour12: true }); const messageHTML = ` <div class="message ${data.username === userName ? 'self' : 'other'}"> <div class="message-content"> <b>${data.username}</b>: ${data.message} </div> <div class="message-time"> ${currentTime} </div> </div> `; document.querySelector('#chat-messages').innerHTML += messageHTML; } else { … -
Django formset with CBV: unicity constraint pass form_valid()
I try to use formset and CBV CreateView for a treatment model but validation failed. I am quite lost with validation logic in my view. I have added a try/catch in form_valid method to manage unicity constraint but this might not be the right way to do. Moreover, other form validations are not displayed in my template. @method_decorator(login_required, name="dispatch") class TraitementFormSetCreate(SuccessMessageMixin, CreateView): model = Traitement form_class = TraitementForm template_name = "ecrf/traitements_form.html" success_message = "Fiche Traitement créée." success_url = reverse_lazy('ecrf:patient_list') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['formset'] = TraitementFormSet(queryset=Traitement.objects.filter(pat=self.kwargs['pk'])) context['action'] = 'create' context['patient'] = Patient.objects.get(ide=self.kwargs['pk']) context['model_name'] = self.model._meta.model_name context['is_locked'] = self.object.ver if self.object else None return context def post(self, request, *args, **kwargs): self.object = self.get_object() # assign the object to the view formset = TraitementFormSet(request.POST) if formset.is_valid(): return self.form_valid(formset) else: return self.form_invalid(formset) def form_valid(self, formset): print('valid') patient = Patient.objects.get(ide=self.kwargs["pk"]) traitements = formset.save(commit=False) for traitement in traitements: traitement.pat = patient traitement.arv_sai_log = self.request.user.username try: traitement.save() except IntegrityError: formset.errors.append(ValidationError('Une fiche Traitement ARV existe déjà pour ce patient avec ce numéro')) context = self.get_context_data(formset=formset) return self.render_to_response(context) return redirect("ecrf:patient_list") def form_invalid(self, formset): print('invalid',formset.errors) context = self.get_context_data(formset=formset) return self.render_to_response(context) -
Django how to handle exception (0, '') while executing sql
settings.py: import configparser config = configparser.RawConfigParser() config.read('/home/forge/django_application/config.ini') DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': config['mysqlDB']['database'], 'USER': config['mysqlDB']['user'], 'PASSWORD': config['mysqlDB']['password'], 'HOST': config['mysqlDB']['host'], 'PORT': '3306', 'CONN_MAX_AGE' : 200, } } __init__.py import pymysql pymysql.install_as_MySQLdb() views.py: cursor = "" def index(request): email_content = "" global cursor cursor = connection.cursor() try: for key, value in request.POST.items(): if key == "body-html": email_html_content = value While I running there is coming exception at the server (0, ''). Is there any solution to fix the mysql exception which handle multiple script. -
Django Complex Query Multiple Models
I have these models and need to make the query below class Quote(models.Model): company = models.ForeignKey( Company, on_delete=models.CASCADE, ) status = models.ForeignKey( StatusType, on_delete=models.CASCADE, ) class QuoteStatusHistory(StatusHistoryBase): quote = models.ForeignKey(Quote, on_delete=models.CASCADE) create_date = models.DateTimeField(auto_now_add=True) class StatusType(models.Model): type_class = models.CharField(max_length=10, choices=COMMON.CLASS_STATUS_TYPE) type_code = models.CharField(max_length=50) type_name = models.CharField(max_length=100) Here is the query: SELECT qt.id ,(SELECT qst.create_date FROM quote_status_history qst JOIN status_type st ON (type_class = 'QUOTE' AND type_code = 'AVAILABLE' AND qst.status_type_id = st.id) WHERE qst.quote_id = qt.id) send_date FROM quote qt WHERE qt.company_id = 90; Currently, I'm just doing a query_set to get all the Quotes for the specific company, and then loop through the all the company.quotes records in order to get the create_date from the QuoteStatusHistory, but the problem is the performance... it will hit database for each record and it will take forever to load the data. What is the most efficient way to get the data from this specific query? -
Linking a custom HTML form with a django model form
I want to connect my model forms to Html forms with horizontal fields. How do I manually render each field. I have tried to implement with no success. With the following method, I have manually render the fields but the form is not saving the data to the database. #add_user.html form action="#" method="POST"> {% csrf_token %} <div class="row"> <div class="col-xl-6"> <div class="form-group row"> <label class="col-lg-3 col-form-label">{{user_form.first_name.label_tag}}</label> <div class="col-lg-9"> {{ user_form.first_name }} </div> </div> <div class="form-group row"> <label class="col-lg-3 col-form-label">{{user_form.last_name.label_tag}}</label> <div class="col-lg-9"> {{ user_form.last_name }} </div> </div> </div> <div class="col-xl-6"> <div class="form-group row"> <label class="col-lg-3 col-form-label">{{user_form.password1.label_tag}}</label> <div class="col-lg-9"> {{ user_form.password1 }} </div> </div> <div class="form-group row"> <label class="col-lg-3 col-form-label">{{user_form.password2.label_tag}}</label> <div class="col-lg-9"> {{ user_form.password2 }} </div> </div> <button type="submit" class="btn btn-primary text-end">Submit</button> </div> </div> </div> </div> -
python, django, api making
I got Attribute Error:'GenericForeignKey' object has no attribute 'get_lookup'.How to solve this error? I tried this in django api making project.Everytime I get this error message.This occurs in model and viewsets of project. -
Unresolved attribute warnings when inheriting from GenericViewSet in Django with custom Mixin
I'm using Django and Django REST Framework to develop a web application. I have a custom ViewSet called ProductsViewSet that inherits from CreateAndSaveUserMixin, RetrieveModelMixin, and GenericViewSet. The code is as follows: class ProductsViewSet(CreateAndSaveUserMixin, RetrieveModelMixin, GenericViewSet): queryset = Product.objects.none() serializer_class = ProductsSerializer The CreateAndSaveUserMixin is defined as: class CreateAndSaveUserMixin: def create(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data, context=self.get_serializer_context()) if serializer.is_valid(): if isinstance(request.user, Cognito): response = serializer.save(created_by=request.user) else: response = serializer.save() return JsonResponse(self.serializer_class(response).data, safe=False) return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST) The issue I'm experiencing is that my IDE, PyCharm, shows the following warnings when I'm working with the CreateAndSaveUserMixin: Unresolved attribute reference 'serializer_class' for class 'CreateAndSaveUserMixin' Unresolved attribute reference 'get_serializer_context' for class 'CreateAndSaveUserMixin' Although my application functions correctly, the editor doesn't recognize these attributes that come from the base class GenericViewSet, which I'm inheriting in my view rather than in my mixin. How can I resolve these warnings in PyCharm and ensure that the editor correctly recognizes the inherited attributes from GenericViewSet in my CreateAndSaveUserMixin? Any help or suggestions would be greatly appreciated. Thank you in advance! i tried declare serializer_class and get_serializer_context in the custom mixin like: serializer_class = None get_serializer_context = None but only works for serializer_class -
I have two errors because of Django or Apache
Two errors: Error 404 (Not Found) on POST request to http://localhost/upload-avatar/ and SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON.When I try to send a POST request to http://localhost/upload-avatar/ I get a POST error http://localhost/upload-avatar/ 404 (Not Found) and a SyntaxError: Unexpected token '<', "< !DOCTYPE "... is not valid JSON. I would like to understand what is the reason and how to fix this problem. There are suspicions that the problem is in Apache. I am using wamp. I connected Django after some time of using and writing wamp code. I configured Apache. I also checked the routing settings and the server startup, but the problem remains. I ask for help in identifying and eliminating this problem. Thank you in advance! Code: JS: PhotoUpload.addEventListener('change', function() { const file = this.files[0]; if (file) { const reader = new FileReader(); reader.addEventListener('load', function() { photo.setAttribute('src', this.result); photo.classList.remove('alt-centered'); PhotoUpload.style.display = 'none'; const formData = new FormData(); formData.append('photo', file); fetch('/upload-avatar/', { method: 'POST', body: formData }) .then(response => response.json()) .then(data => { console.log(data); }) .catch(error => { console.error('Error:', error); }); }); reader.readAsDataURL(file); } else { photo.setAttribute('src', '#'); photo.classList.add('alt-centered'); PhotoUpload.style.display = 'block'; } }); }; views.py from django.shortcuts import render from django.views.decorators.csrf import … -
request.user return AnonymousUser in django, react project
I have a web project what back-end is coded with django and front-end is coded with react. In my project, i want to create an order to a special user so this part of project needs to know the user but when i used request.user it returned AnonymousUser. here are the react, axios code and views.py with rest_framework: react code // Hook to save game id and price const [all, setAll] = useState({'game': 0, 'price': 0}); // get state const location = useLocation(); const state = location.state; useEffect(() => { setAll({'game': state[0]}, 'price': suggestion); }, []) // To check user confirm suggestion and make order api. const orderApi = async (e) => { e.preventDefault(); try { // console.log({'state': state[0], 'suggestion': suggestion}); console.log(all); const {status} = await axios.post('http://127.0.0.1:8000/api-1/order/create/', all); if (status === 201) { console.log('created'); } } catch (err) { console.log(err) } } views.py from rest_framework import status from rest_framework.response import Response from . import serializer from rest_framework.decorators import api_view from . import models from game.models import Game @api_view(['GET', 'POST']) def orderCreate(request): # Here my program return AnonymousUser print(str(request.user) + '\n') if request.method == 'POST': ....... orders = models.Order.objects.all() serialized = serializer.OrderSerializer(orders, many=True) return Response(serialized.data, status=status.HTTP_200_OK) To write a clean code … -
Using enums in Django with error ModuleNotFoundError: No module named 'models'
I am trying to use enums in my unit tests but I'm getting an error when I try to import them. An excerpt from models.py: class SeekingConstants: MEN = 'Men' WOMEN = 'Women' BOTH_MEN_AND_WOMEN = 'Both men and women' An excerpt from test_user_api.py: from models import SeekingConstants ... def test_update_user_seeking_choice(self): """Part 1: Update the seeking choice from nothing""" payload = { 'email': 'test@example.com', 'seeking_choice': SeekingConstants.WOMEN } res = self.client.patch(ME_URL, payload) self.user.refresh_from_db() self.assertEqual(self.user.email, payload['email']) self.assertTrue(self.user.seeking_choice, payload['seeking_choice']) self.assertEqual(res.status_code, status.HTTP_200_OK) """Part 2: Update an existing seeking choice""" new_payload = { 'email': 'test@example.com', 'seeking_choice': SeekingConstants.BOTH_MEN_AND_WOMEN } res = self.client.patch(ME_URL, new_payload) self.user.refresh_from_db() self.assertEqual(self.user.email, payload['email']) self.assertTrue(self.user.seeking_choice, payload['seeking_choice']) self.assertEqual(res.status_code, status.HTTP_200_OK) I'm not sure why I can't import this enum or how I should import this enum. -
Trying to implement the django-formset library but I am unable to get any of the buttons to work. They are completely non-responsive
I am trying to utilize the django-formset library to create dynamic forms. However, I am unable to get any of the buttons to work (whether they're add/submit or add forms). The only error in the javascript console was the following: Uncaught DOMException: Failed to read the 'cssRules' property from 'CSSStyleSheet': Cannot access rules at Object.i [as convertPseudoClasses] (http://127.0.0.1:8001/static/formset/js/chunk-KFPGMBXM.js:1:354) at http://127.0.0.1:8001/static/formset/js/django-formset.js:25:29909 This is my first time working with django, html, css, javascript, and jquery but as far as I could trace the issue, I thought it maybe had something to do with not loading the typescript implementation of the 'click' webelement based on this error. But I got stuck tracing the error and so I tried to simplify/isolate the issue by creating a new project and copying the examples in the documentation. I also though there could be a conflict or issue with one of my templates, another library, or with a javascript function... ...but I can't get even the simplest model/form button to work using the example in Chapter 9 of the documentation. So I'm wondering if there's something really basic I'm missing. The following example doesn't throw any errors in the browser console but results in the same dead … -
"The client was disconnected by the server because of inactivity" using an async function in Django
I'm using Django 4.2 connected to a MySQL 8 database. I'm using asyncio for a function I really need to run asynchronously: example_object = asyncio.run(example(request)) async def example(request): object = await ModelExample.objects.filter(example=example).afirst() return object I started by having the error in the await line: MySQL server has gone away Then, by manually closing connection like: example_object = asyncio.run(example(request)) connection.close() I started having the following error: The client was disconnected by the server because of inactivity. See wait_timeout and interactive_timeout for configuring this behavior This error don't happen right away, but after a few hours (maybe 8h, like the default wait_timeout variable) after I restart the (nginx) server. Things that I tried: Adding close_old_connections() before asyncio.run. Don't understand why there is an inactive connection left open at all. Increasing the wait_timeout value and interactive_timeout variables in my MySQL config file. I find it very strange that this had no impact at all but the "SHOW VARIABLES" command shows me they are indeed currently set to 31536000. Then I thought that maybe the connection from Django is somehow independent of that and tried setting CONN_HEALTH_CHECKS option to True, in the hopes that "if the health check fails, the connection will be reestablished …