Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to show two list of data in flutter
I am trying to fetch an api using flutter and dart and http package. Here in my code i am trying to fetch this api model : class OfferModel2 { OfferModel2({ required this.offer, required this.manager, }); late final List<Offer> offer; late final List<Manager> manager; OfferModel2.fromJson(Map<String, dynamic> json) { offer = List.from(json['offer']).map((e) => Offer.fromJson(e)).toList(); manager = List.from(json['manager']).map((e) => Manager.fromJson(e)).toList(); } Map<String, dynamic> toJson() { final _data = <String, dynamic>{}; _data['offer'] = offer.map((e) => e.toJson()).toList(); _data['manager'] = manager.map((e) => e.toJson()).toList(); return _data; } } class Offer { Offer({ required this.id, required this.offerTitle, required this.image, required this.user, required this.click, required this.category, required this.packages, }); late final int id; late final String offerTitle; late final String? image; late final User user; late final int click; late final Category category; late final List<Packages> packages; Offer.fromJson(Map<String, dynamic> json) { id = json['id']; offerTitle = json['offer_title']; image = json['image']; user = User.fromJson(json['user']); click = json['click']; category = Category.fromJson(json['category']); packages = List.from(json['packages']).map((e) => Packages.fromJson(e)).toList(); } Map<String, dynamic> toJson() { final _data = <String, dynamic>{}; _data['id'] = id; _data['offer_title'] = offerTitle; _data['image'] = image; _data['user'] = user.toJson(); _data['click'] = click; _data['category'] = category.toJson(); _data['packages'] = packages.map((e) => e.toJson()).toList(); return _data; } } class User { User({ required this.id, required … -
Game Level data for each user in Database
I'm creating a game in Django where there are like 500 levels. How do I store game level data for each user in database ( data can be stars for each level ). The game is more like the candy crush where each user earns stars for each level. Is JSON suitable for this? Should I use a separate table for each level? Or should I use single table for all levels with level_id as Primary Key and user_id as Foreign Key? -
Running python/python3 manage.py runserver inside a venv responds with "wrong architecture" error
I spent about all day yesterday attempting to troubleshoot this issue, I've done everything from reinstalling Django, pipenv, etc to changing the Rosetta settings in my terminal. Below is what my terminal responds with after running the command in the venv. I have classmates that are also running on a M1 chip and aren't having this issue. I have psycopg2 installed as well and have verified it is by using the pip list command. This is my first post on Stackoverflow so I apologize for any inconsistencies or formatting. ((django-env) ) bash-3.2$ python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/Users/stevenlopez/.local/share/virtualenvs/django-env-KW2l6c6v/lib/python3.9/site-packages/django/db/backends/postgresql/base.py", line 25, in <module> import psycopg2 as Database File "/Users/stevenlopez/.local/share/virtualenvs/django-env-KW2l6c6v/lib/python3.9/site-packages/psycopg2/__init__.py", line 51, in <module> from psycopg2._psycopg import ( # noqa ImportError: dlopen(/Users/stevenlopez/.local/share/virtualenvs/django-env-KW2l6c6v/lib/python3.9/site-packages/psycopg2/_psycopg.cpython-39-darwin.so, 2): no suitable image found. Did find: /Users/stevenlopez/.local/share/virtualenvs/django-env-KW2l6c6v/lib/python3.9/site-packages/psycopg2/_psycopg.cpython-39-darwin.so: mach-o, but wrong architecture /Users/stevenlopez/.local/share/virtualenvs/django-env-KW2l6c6v/lib/python3.9/site-packages/psycopg2/_psycopg.cpython-39-darwin.so: mach-o, but wrong architecture During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/opt/homebrew/Cellar/python@3.9/3.9.7_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 973, in _bootstrap_inner self.run() File "/opt/homebrew/Cellar/python@3.9/3.9.7_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "/Users/stevenlopez/.local/share/virtualenvs/django-env-KW2l6c6v/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/stevenlopez/.local/share/virtualenvs/django-env-KW2l6c6v/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 115, in inner_run autoreload.raise_last_exception() File "/Users/stevenlopez/.local/share/virtualenvs/django-env-KW2l6c6v/lib/python3.9/site-packages/django/utils/autoreload.py", line 87, in … -
Django bootstrap: File is not being sent with the Post when using a modal form
In my Django App there is a page where users can upload files from their local machine (and do other things). The flow I built is so that users click on "+", a modal form comes up, users browse for a file on their local machine, select it and when they click save I submit the form. However, for some reason, the file isn't getting posted but it seems like I am posting only the name of the file. But I can't figure out why. file page ... <div class="list-files__btn-plus-wrp"> <a class="list-files__btn-plus" href="#" data-bs-toggle="modal" data-bs-target="#modal"> <img src="{% static 'action/img/project/files/icon_plus-file.svg' %}" alt="+"> </a> </div> {% include 'action/forms/modals/modal.html' %} modal.html <div class="modal fade" tabindex="-1" role="dialog" id="modal" > <div class="modal-dialog" role="document"> <div class="modal-content"> <!-- Popup --> <div class="pop-up-form"> <div class="pop-up-form__wrp"> <!-- Title --> <div class="pop-up-form__title-wrp"> <h2 class="pop-up-form__title">Dialog Title</h2> </div> <!-- END Title --> <!-- Form --> <form action="{% url 'action:project_files' project_id=project.id %}" method="POST" class="pop-up-form__form"> {% csrf_token %} <!-- Input File Name --> <div class="pop-up-form__input-wrp"> <label class="pop-up-form__label" for="fileName">File Name</label> <input class="pop-up-form__input" id="fileName" name="fileName" type="text" placeholder="File Name"> </div> <!-- END Input File Name --> <!-- Input Link --> <div class="pop-up-form__input-wrp"> <!-- Link --> <div class="pop-up-form__input-two-wrp"> <label class="pop-up-form__label" for="inputLink">Link</label> <input class="pop-up-form__input" id="inputLink" name="inputLink" type="text" placeholder="https://"> </div> … -
Djano how to apply multiple logic from same fuction depend on user page visite?
I wrote an function for download csv file. I have two type of user doctor and patient. When any user visit patient.html page he can download all patient data. I know I can write another function for downloads all doctor data when anyone visit doctor.html page but I want to do it in same function. here is my code: def exportcsv(request,slug=None): response = HttpResponse(content_type='text/csv') writer = csv.writer(response) all_patient = Patient.objects.all() all_doctor = Doctor.objects.all() if slug == None: if all_patient: response ['Content-Disposition'] = 'attachment; filename=AllPatientData'+str(datetime.date.today())+'.csv' writer.writerow(['patient_id','patient_name','date_of_birth','age','phone','email','gender','country','state','city','zip_code','address']) for i in all_patient: writer.writerow([i.patient_id,i.patient_name,i.date_of_birth,i.age,i.phone,i.email,i.gender,i.country,i.state,i.city,i.zip_code,i.address]) if all_doctor: response ['Content-Disposition'] = 'attachment; filename=AllDoctorData'+str(datetime.date.today())+'.csv' writer.writerow(['docter_id_num','doctor_name','doctor_speciality','doctor_experience','date_joined']) for i in all_doctor: writer.writerow([i.docter_id_num,i.doctor_name,i.doctor_speciality,i.doctor_experience,i.date_joined]) return response my urls.py path('all-doctor/',AllDoctors.as_view(),name='all-doctor'), now it's downloading all patients and doctor data together. I want it will download only all doctor data when visit doctor.html page and all patient data when visit patient.html page. any idea how I can do it from this exportcsv view function? I think we can add different url parameter in exportcsv view but I don't know how to do that. -
File Structure in Django
I am learning Django and making an ecommerce website. My File Structure is as follows: [![My project File Structure][1]][1] Now I am uploading some pictures but could not able to access in the web. {% load static %} <div class="card" style="width: 18rem;"> <img src='{% static "images/aws.png" %}' class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">Card title</h5> <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p> <a href="#" class="btn btn-primary">Go somewhere</a> The above example is of an part of an carousal. Please help where I am missing something. How to give link to images in my web. [1]: https://i.stack.imgur.com/Eio3H.jpg -
DetalView get_context_data into ListView
I have a bit of a long question. I am writing a bookkeeping system in django I have a model for supplier as follows class Supplier(models.Model): supplier_name = models.CharField(max_length=50) supplier_number = models.IntegerField() def __str__(self): return self.supplier_name and also the expense model as class Expense(models.Model): invoice_number = models.CharField(max_length=50) invoice_date = models.DateField() supplier_name = models.ForeignKey(Supplier, on_delete=models.CASCADE, related_name='expenses') description = models.CharField(max_length=100) def amt_excl_vat(self): if self.supplier_name.intra_community is None: vat_amount = (Decimal(self.expense_vat.vat_rate)/100)/(1+(Decimal(self.expense_vat.vat_rate)/100))*self.amt_incl_vat amt_excl_vat = self.amt_incl_vat - vat_amount else: vat_amount = 0 amt_excl_vat = self.amt_incl_vat - vat_amount return amt_excl_vat in my SupplierDetailView(DetailView) I calculated some values in def get_context_data like def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) pk = self.kwargs["pk"] supplier = get_object_or_404(Supplier, pk=pk) expenses = supplier.expenses.all() expenditure_ex = 0 for item in expenses: expenditure_ex += item.amt_excl_vat() context['expenditure_ex'] = expenditure_ex return context the results give me correct values. I want to get the value of expenditure_ex in the SupplierListView(ListView) sorry for a long question TIA -
Nginx Reverse Proxy very slow on image upload
I use Nginx as a Reverse Proxy for a Django Project with Gunicorn. It is used for https. Everything on the site is loaded fast, except when I send a POST request with multipart form data. Then it takes 26 seconds for a 2 Megabyte image to process the request. For a 60 Kilobyte image it takes several seconds but still way too long. I measured the processing time of the Django view with the python time module and got around 80 milliseconds. During testing on a local development server it took around a second to process the request. And on the deployment server all media files are served quickly. So I guess the cause is an unsuitable configuration of Nginx with the multipart form request. My conf file is mostly untouched. I tried all StackOverflow solutions with modified cache settings and once with denabled cache but without success. Is there an information and configuration that I missed? -
How can I fix the internal error in Django?
I don't have a lot of experience in Django and am a fairly green developer. When I run the localhost I keep getting a Internal Error. I have tried most of the solutions to similar problems here and none works. Can anyone help me? The code is not mine so I don't want to alter it as such either. Here is a picture of the errors I keep getting: Error Page -
How to efficiently add objects to ManyToManyFields of multiple objects Django python?
How to efficiently add objects to ManyToManyFields of multiple objects? def handle(self, *args, **kwargs): shops = MyShop.objects.all() for shop in shops: month_invoice = shop.shop_order.annotate(year=TruncYear('created'), month=TruncMonth('created')).values( 'year', 'month', 'shop_id' ).annotate(total=Sum(ExpressionWrapper( (F('item_comission') / 100.00) * (F('price') * F('quantity')), output_field=DecimalField())), ).order_by('month') for kv in month_invoice: a = ShopInvoice.objects.create(shop_id=kv['shop_id'], year=kv['year'], month=kv['month'], total=kv['total']) test = shop.shop_order.filter(created__month=kv['month'].month, created__year=kv['year'].year) for t in test: a.items.add(t.id) -
How to calculate total price in django?
I'm building an ecommerce website and trying to calculate the total price of the products in views.py but I'm getting an error. Here is my code: @login_required(login_url='/customer/login') @customer() def addtocart(request): if request.user.is_authenticated: buyer = request.user.is_customer cart = Cart.objects.filter(buyer = buyer) amount = 0.00 cart_products = [p for p in Cart.objects.all() if p.buyer == buyer] if cart_products: for p in cart_products: t_amount = (p.products.discounted_price) total_amount += t_amount return render(request, 'Shop/cart.html', {'cart': cart, 'total_amount': total_amount}) This is what it says in the browser: local variable 'total_amount' referenced before assignment. Thank you -
Django loads HTML but doesn't couple static file
I am having trouble serving the static file (CSS) to my HTML page. The HTML loads but the CSS gets the following error on the console: GET http://myip/static/registration/style.cc net::ERR_ABORTED 404 (Not found) This is how I am telling the server to load the HTML with the css: <doctype !html> <html> <head> {% load static %} <link rel="stylesheet" href="{% static 'registration/style.css' %}"> </head> THis is my file structure : omeusite ├── db.sqlite3 ├── manage.py ├── omeusite │ ├── asgi.py │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-38.pyc │ │ ├── settings.cpython-38.pyc │ │ ├── urls.cpython-38.pyc │ │ └── wsgi.cpython-38.pyc │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── quizz │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ │ ├── 0001_initial.py │ │ ├── __init__.py │ │ └── __pycache__ │ │ ├── 0001_initial.cpython-38.pyc │ │ └── __init__.cpython-38.pyc │ ├── models.py │ ├── nano.save │ ├── __pycache__ │ │ ├── admin.cpython-38.pyc │ │ ├── apps.cpython-38.pyc │ │ ├── __init__.cpython-38.pyc │ │ ├── models.cpython-38.pyc │ │ ├── urls.cpython-38.pyc │ │ └── views.cpython-38.pyc │ ├── templates │ │ └── quizz │ │ ├── detail.html │ │ ├── index.html │ │ └── results.html │ ├── tests.py │ ├── … -
I want to fetch the data using api in flutter just like django
I am trying to build freelancing type app. I am using flutter and for my backend data i created an api using django rest framework. Here is the models.py: class Package(models.Model): management_duration_choices = ( ("1", "1"), ("2", "2"), ("3", "3"), ("4", "4"), ("5", "5"), ("6", "6"), ("7", "7"), ("8", "8"), ("9", "9"), ("10", "10"), ("11", "11"), ("12", "12"), ("13", "13"), ("14", "14"), ("15", "15") ) title = models.CharField(max_length=120) delivery_time = models.ForeignKey( DeliveryTime, on_delete=models.CASCADE, null=True) package_desc = models.TextField(null=True) revision_basic = models.ForeignKey(Revision, on_delete=models.SET_NULL, null=True, blank=True, related_name="revision_basic") revision_standard = models.ForeignKey(Revision, on_delete=models.SET_NULL, null=True, blank=True, related_name="revision_standard") revision_premium = models.ForeignKey(Revision, on_delete=models.SET_NULL, null=True, blank=True, related_name="revision_premium") num_of_pages_for_basic = models.ForeignKey(NumberOfPage, on_delete=models.SET_NULL, null=True, related_name="num_of_pages_for_basic", blank=True) num_of_pages_for_standard = models.ForeignKey(NumberOfPage, on_delete=models.SET_NULL, null=True, related_name="num_of_pages_for_standard", blank=True) num_of_pages_for_premium = models.ForeignKey(NumberOfPage, on_delete=models.SET_NULL, null=True, related_name="num_of_pages_for_premium", blank=True) is_responsive_basic = models.BooleanField(default=False, null=True, blank=True) is_responsive_standard = models.BooleanField(default=False, null=True, blank=True) is_responsive_premium = models.BooleanField(default=False, null=True, blank=True) setup_payment = models.BooleanField(default=False, null=True, blank=True) will_deploy = models.BooleanField(default=False, null=True, blank=True) is_compitable = models.BooleanField(default=False, null=True, blank=True) supported_formats = models.ManyToManyField(FileFormats, blank=True) # For Logo Design provide_vector = models.BooleanField(default=False, null=True, blank=True) is_3dmockup = models.BooleanField(default=False, null=True, blank=True) is_high_res_for_basic = models.BooleanField(default=False, null=True, blank=True) is_high_res_for_standard = models.BooleanField(default=False, null=True, blank=True) is_high_res_for_premium = models.BooleanField(default=False, null=True, blank=True) will_sourcefile_for_basic = models.BooleanField(default=False, null=True, blank=True) will_sourcefile_for_standard = models.BooleanField(default=False, null=True, blank=True) will_sourcefile_for_premium = models.BooleanField(default=False, null=True, blank=True) # For Digital … -
Razorpay payment integration django
I'm trying to integrate razorpay payment gateway for my ecommerce website . It pops up following message " Invalid amount(should be passed in integer paise . Minimum value is 100 paise i.e Rs 1)" Here are the relevant files views.py checkout def checkout(request): form = CheckoutForm(request.POST or None) cart_id = request.session.get("cart_id", None) if cart_id: cart_obj = Cart.objects.get(id=cart_id) if form.is_valid(): form.instance.cart = cart_obj form.instance.subtotal = cart_obj.total form.instance.discount = 0 form.instance.total = cart_obj.total form.instance.order_status = "Order Received" del request.session['cart_id'] form.save() form=CheckoutForm() return render(request,"pay.html",{"form":form}) else: cart_obj = None return render(request,"checkout.html",{'cart':cart_obj,'form':form}) pay def pay(request): orders=form o_id=orders.id orderr=Order.objects.get(id=o_id) order_amount=orderr.total order_currency="INR" order=client.order.create(dict(amount=order_amount,currency=order_currency)) context={ 'order_id':order['id'], 'amount':order['amount'], 'key_id':key_id } return render(request,"pay.html",context) pay.html <html> <head> <title>Pay</title> </head> <body> <button id="rzp-button1">Pay</button> <script src="https://checkout.razorpay.com/v1/checkout.js"></script> <script> var options = { "key": "{{key_id}}", // key_id has been generated "amount":"{{amount}}", // Amount is in currency subunits. Default currency is INR. Hence, 50000 refers to 50000 paise "currency": "INR", "name": "Acme Corp", "description": "Test Transaction", "image": "https://example.com/your_logo", "order_id": "{{order_id}}", //This is a sample Order ID. Pass the `id` obtained in the response of Step 2 "handler": function (response){ alert(response.razorpay_payment_id); alert(response.razorpay_order_id); alert(response.razorpay_signature) }, "theme": { "color": "#99cc33" } }; var rzp1 = new Razorpay(options); rzp1.on('payment.failed', function (response){ alert(response.error.code); alert(response.error.description); alert(response.error.source); alert(response.error.step); alert(response.error.reason); alert(response.error.metadata.order_id); alert(response.error.metadata.payment_id); }); document.getElementById('rzp-button1').onclick … -
How to convert Canvas to SimpleDocTemplate?
I am writing in django. And i have to return pdf using buffer and SimpleDocTemplate. But i can only work with Canvas. Is there any easy way to do it? -
Can't load django project with apache
This is my directory structure pic and this is what i added to the apache httpd.conf file LoadModule wsgi_module modules/mod_wsgi.so <IfModule wsgi_module> WSGIScriptAlias / "C:/Users/Administrator/PycharmProjects/pythonProject/TCL/TCL/wsgi.py" WSGIPythonPath "C:/Users/Administrator/PycharmProjects/pythonProject/TCL" <Directory "C:/Users/Administrator/PycharmProjects/pythonProject/TCL"> <Files wsgi.py> Allow from all Require all granted </Files> </Directory> WSGIPythonHome "C:/Users/Administrator/AppData/Local/Programs/Python/Python37" Alias /media/ C:/Users/Administrator/PycharmProjects/pythonProject/TCL/media/ Alias /static/ C:/Users/Administrator/PycharmProjects/pythonProject/TCL/static/ <Directory C:/Users/Administrator/PycharmProjects/pythonProject/TCL/static> Allow from all Require all granted </Directory> <Directory C:/Users/Administrator/PycharmProjects/pythonProject/TCL/media> Allow from all Require all granted </Directory> </IfModule> i installed port 8080 and 4433 but both can't load -
Django CMS drag and drop problems
when changing the arrangement in the right toolbar, the selected element always slides strongly to the right into the void. In this way, it is not possible to restructure the arrangement sensibly. Does anyone have the same problem or a solution? -
Unable to make django-master-password work
I would like to enable a master password in my DRF (React.js + Django) website using django-master-password. After following the instructions as best as I could understand them, here are the relevant parts of settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_extensions', # 3rd party apps 'rest_framework', 'rest_framework.authtoken', 'dj_rest_auth', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'dj_rest_auth.registration', 'corsheaders', 'import_export', 'django_admin_logs', 'master_password', # Local apps 'users', # Responsible for all actions pertaining to user model 'content', 'payments' ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', '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', ] AUTHENTICATION_BACKENDS = ( "django.contrib.auth.backends.ModelBackend", "allauth.account.auth_backends.AuthenticationBackend", "master_password.auth.ModelBackend" ) MASTER_PASSWORDS = { 'Abc123': None } However, when I try to log into a user account with Abc123 as password, I still get the response {non_field_errors: ["Unable to log in with provided credentials."]}. What am I missing? -
Exclude history fields from django simples history on to_representation method in django rest framework
I'm using Django Rest Framework with django-simple-history and currently I would like to return the history modifications in my rest API, currently it is doing well but I would like to hide some fields. This is the currently output: But, I don't need id, history_id, etc. my implementation is the same of alexander answer in this post. What i've tried: def to_representation(self, data): representation = super().to_representation(data.values()) del representation[0]['history_id'] return representation But it does not seem the best way to do it. If you have some hint about how to do it the correct way I would like to know. Thanks in advance! -
DJANGO DEBTORS LIST
i have two model with the same names, i want to display its value(display repeated names once) and its summation. what i have been achieved so far is to to do only for Invoice table and working perfect, but when i want to add receiptmodel doesn1t not arrange as invoice arranged model.py from django.db import models class invoice(models.Model): customer = models.CharField(max_length=100, null=False) total_amount = models.DecimalField(max_digits=20, decimal_places=2) class Meta: db_table="invoice" class ReceiptModel(models.Model): customer = models.CharField(max_length=100, blank=True, unique=False) to_amount = models.CharField(max_length=100, blank=True, unique=False) class Meta: db_table="receiptmodel" view.py from django.shortcuts import render, redirect, get_object_or_404, reverse from django.contrib import messages from django.http import HttpResponse, HttpResponseRedirect, JsonResponse from django.forms import modelformset_factory #from django.forms import ModelForm from .models import * from .forms import *#UserRegisterForm, InvoiceForm, LineItemFormset, NewCustomerForm, CustomerReceiptForm from django.urls import * from itertools import chain from operator import attrgetter from django.db.models import Sum, Q def ReceivableReport(request): #still not working receivable_inv = Invoice.objects.values("customer").annotate(totinv= Sum('total_amount')) receivable_rec = ReceiptModel.objects.values("customer").annotate(totrec= Sum('to_amount')) #zipped_data = zip(receivable_inv, receivable_rec) #zipped_data = list(chain(receivable_inv,receivable_rec)) context = { 'receivable_inv':receivable_inv, 'receivable_rec':receivable_rec, # 'zipped_data ':zipped_data, } return render(request, "reports/debtorlist.html", context) debtorlist.html <table style="width: 50%;"> <thead> <tr> <th>Name</th> <th>Inv Amount</th> <th>Rec Amount</th> </tr> </thead> {% for receivable_inv in receivable_inv%} <tbody> <tr> <td>{{ receivable_inv.customer }}</td> <td>{{ receivable_inv.totinv}}</td> <td>{{ receivable_rec.totrec}}</td> </tr> … -
How Django handle multiple requests send at the same time
I have checked most of the comments and the answer always was that Django (on local machine) handles only one request at a time. I have simple django application with view function that waits 5 seconds. When I run two the same GET requests in postman, I can see both requests are handled in the same time, they are not queued or overwritten one by another. My question is how it is possible? My view code: def wait_some_time(request): import time print("Printed immediately.") time.sleep(5) print("Printed after 5 seconds.") return Response({'message': 'nothing'}) Postman request: Postman request (I'm sending 2 requests in the same time) Console output: Printed immediately. Printed immediately. Printed after 5 seconds. [05/Jan/2022 14:55:35] "GET /api/user/test HTTP/1.1" 200 21 Printed after 5 seconds. [05/Jan/2022 14:55:36] "GET /api/user/test HTTP/1.1" 200 21 -
nginx/gunicorn/django 403 forbidden error
I've built a small website using django, gunicorn, and nginx. So far what I have for /etc/nginx/sites-available/blog is upstream django { server 127.0.0.1:8080; } server { listen 172.17.0.1:80; server_name my.broken.blog; index index.html; location = /assets/favicon.ico { access_log off; log_not_found off; } location /assets { autoindex on; alias /var/www/html/mysite/assets; } location / { autoindex on; uwsgi_pass unix:///run/uwsgi/django/socket; include /var/www/html/mysite/mysite/uwsgi_params; proxy_pass http://unix:/run/gunicorn.sock; } } The error.log file shows that 2022/01/05 13:50:55 [error] 194#194: *2 directory index of "/var/www/html/" is forbidden, client: ip-address, server: _, request: "GET / HTTP/1.1", host: "my.broken.blog" -
Whitelisted email in SOCIAL-AUTH-APP-DJANGO
I am figuring how to restrict people to log in to my website. I am using the Python library social-auth-app-django. In the documentation they said to add auth_allowed to the pipeline SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.social_auth.associate_by_email', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) But I am not sure how to configure my code. I even added SOCIAL_AUTH_GOOGLE_WHITELISTED_EMAILS = ['me@foo.com'] But still it doesn't seem to work -
What is ajax gets invalid form, How can i render it?
I am working with Django and Ajax. With the help of jQuery, i successfully sent form data to server and able to validate it. Problem arrive when form is invalid, i want that, if the form is invalid, ajax get the invalid form and render it to same template with errors like all invalid forms do. How Can i do it ? -
Django & Djoser 'NoneType' object has no attribute 'lower' 'NoneType' object has no attribute 'lower'
I keep having an error whenever I try to PATCH in order to update a specific user info. As per Djoser documentation, the endpoint is located in /users/me/ https://djoser.readthedocs.io/en/latest/base_endpoints.html#user Everything is working fine except this part. I have a Custom User model and overrided the default (again, as per documentation) 'current_user': 'accounts.serializers.UserCreateSerializer', serializer.py class UserCreateSerializer(UserCreateSerializer): class Meta(UserCreateSerializer.Meta): model = User fields = ('id', 'email', 'first_name', 'last_name', 'is_active') models.py class UserAccountManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): if not email: raise ValueError('Un email est obligatoire') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password): user = self.create_user(email, password) user.is_superuser = True user.is_staff = True user.save() return user class UserAccount(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) phone = models.CharField(max_length=50) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) USERNAME_FIELD = 'email' objects = UserAccountManager() def get_full_name(self): return self.first_name def get_short_name(self): return self.first_name def __str__(self): return self.email What am I missing?