Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: mysterious slow request before timing middleware kicks in
I'm using Django with Sentry to monitor errors and performance. There's one specific endpoint (this doesn't happen with other endpoints) that seems to stall for a few seconds before actually processing the request. It's a very simple endpoint, but it does get called a lot. It seems to do nothing for a few seconds and is waiting on the time before Django middleware is even called. The actual logic that goes into rendering only takes a few hundred milliseconds: something is happening before the Django middleware that causes this to only happen for this view. What could this mean? I don't often see the Django.db.close_old_connections call and I'm hoping someone might have a clue for what might be causing it when the stall is after that, with another stall in the same place towards the end right before close_old_connections is called again. -
can't authenticate username and pasword of another table
my project is a online store, My admin side and store side just use username and password at table User with Superuser permission to login, If login at store admin side login too and vice versa. data User data Customer this is my code views.py def register(request): registered= False last_visit = request.session.get('last_visit',False) if request.method == 'POST': form_user = FormCustumer(data=request.POST) form_por = UserProfileInfoForm(data=request.POST) if (form_user.is_valid() and form_por.is_valid() and form_user.cleaned_data['password'] == form_user.cleaned_data['confirm']): user = form_user.save() #user.set_password(user.password) user.password = make_password('password') user.is_active = True user.save() #profile = form_por.save(commit=False) #profile.user = user if 'image' in request.FILES: user.image = request.FILES['image'] user.save() registered=True email_address = form_user.cleaned_data['email'] subject = 'Chào mừng bạn đến với chúng tôi' message = 'Hi vọng bạn có những giây phút thư giãn và có những lựa chọn mua sắm đúng đắn!' recepient = str(email_address) html_content = '<h2 style="color:blue"><i>Dear Reader,</i></h2>'\ + '<p>Chào mừng bạn đến với <strong>EShop</strong> website.</p>'\ + '<h4 style="color:red">' +message + '</h4>' msg = EmailMultiAlternatives(subject, EMAIL_HOST_USER, [recepient]) msg.attach_alternative(html_content, 'text/html') msg.send() #send_mail(subject,message, EMAIL_HOST_USER,[recepient],fail_silently=False) if form_user.cleaned_data['password'] != form_user.cleaned_data['confirm']: form_user.add_error('confirm', 'Mật khẩu xác nhận không chính xác') print(form_user.errors,form_por.errors) else: form_user = FormCustumer() form_por = UserProfileInfoForm() username = request.session.get('username',0) cart = Cart(request) return render(request, 'store/signin.html',{ 'subcategories': subcategory_list, 'form_user':form_user, 'form_por':form_por, 'registered':registered, 'username':username, 'cart': cart, 'today':now, 'latest':latest, 'last_visit':last_visit, … -
How to accept a file upload in django and send it to a flask api as a file upload?
I have a Flask API running on my localhost that accepts a file as a form data and returns an output. I also have another application that is created using Django that actually faces the user. I'm trying to have it so that a user can upload a file to the Django app and the Django app then forwards the file to the API. So far I've got this code: In Django views.py: url = 'http://127.0.0.1:5000/uploadFile' files = {'file': request.FILES['file']} response = requests.post(url, files=files) In Flask: @app.route("/uploadFile", methods=["GET", "POST"]) def uploadFile(): if request.method == "POST": file = request.files.get("file") I've tested the Flask api using Postman and it works as expected. Running the above code, I get the following output (error): I get a long series of this output repeated several times: Object 5 0 not defined. Overwriting cache for 0 5 And this at the end of it: RecursionError: maximum recursion depth exceeded while calling a Python object -
Django Advice - model_to_dict - User returning ID instead of username
I'm calling the model_to_dict function and it is working, but i want to be able to modify the results before returning. The Author area is currently returning an id number and I want it to return the Username instead. Does anybody know how to make that happen? .model class Comment(models.Model): poopfact = models.ForeignKey(PoopFact, related_name="comments", on_delete=models.CASCADE) author = models.ForeignKey(User, on_delete=models.CASCADE) comment = models.TextField(unique=True, blank=True, null=True) datetime = models.DateTimeField(auto_now_add=True) likes = models.ManyToManyField(User, related_name="comment_likes") .views def comment(request, poopfact_id): ... new_entry = Comment() ... data = model_to_dict(new_entry) return JsonResponse(data, safe=False) -
Need jQuery AJAX response Advice - Passing multiple response['Variables'] in multiple HTML createElements - Django
I'm trying to asynchronously update a comment section on my page which has multiple elements that need to be created and multiple variables that need to be updated. I know how to create multiple elements, but not sure how to update place multiple response variables. I've pretty much replaced all the django templates {{variable}} with a ${response['var']} but it doesn't work. Any advice on this? current html structure with django templates {% for comment in poopfacts %} <div class="row"> <p class="col text-muted fw-light d-inline" style="font-size:10px;"> {{comment.author}} </p> <p class="col text-muted fw-light d-inline" style="font-size:10px;" align="right"> {{comment.datetime}} </p> </div> <p> {{comment.comment}} </p> <p class="d-inline like-count{{comment.id}}"> {{ comment.like_count }} </p> likes <form action="{% url 'like_comment' comment.id %}" class="d-inline like-form" id="{{comment.id}}"> <button type="submit" class="btn btn-link">like</button> </form> {% endfor %} .script success: function(response) { $(`.comment-row${poopfact.id}`).append(` <div class="row"> <p class="col text-muted fw-light d-inline" style="font-size:10px;"> ${response['author']} </p> <p class="col text-muted fw-light d-inline" style="font-size:10px;" align="right"> ${response['datetime']} </p> </div> <p> ${response['comment']} </p> <p class="d-inline like-count${response['id']}"> ${response['datetime']} </p> likes <form action="{% url 'like_comment' ${response['id']} %}" class="d-inline like-form" id="${response['id']}"> <button type="submit" class="btn btn-link">like</button> </form> `) -
Why the checkboxes are not sent though request?
I am doing a form with checkboxes, but I can't make it send to the view. The request only send the csrf token. What I am doing wrong? <form action="select" method="POST"> <div class="form-check"> <input class="form-check-input" type="checkbox" value="{{ subject.id }}" id="flexCheckDefault{{ subject.grouper }}{{ subject.id }}" > <label class="form-check-label" for="flexCheckDefault-{{ subject.name }}"> {{ subject.name }} </label> </div> <button type="submit" class="btn btn-sm btn-primary pull-left"><i class="fa fa-check"></i> Save</button> Request: csrfmiddlewaretoken=VQRxpROz9G9b1ObLSqBX7AP6JaIneD2sW1lxRFNjypEuuKCPOM2GEtoMD383u53S -
Only accept values based on another table ? (MySQL, PostgreSQL, Django)
I'm developing a School/University software and I got stucked in this situation: Table Professor id name 1 Mr. Ward 2 Mr. Smith Table Subject id name 1 Math 2 Physics 3 English Table ProfessorsSubject p_id s_id 1 1 1 2 2 3 (Mr. Ward, Math), (Mr. Ward, Physics) and (Mr. Smith, English) Table StudentClass: id name Building 10 Tenth Grade A 11 Eleventh Grade A Table A: sclass_id subj_id prof_id foo bar 10 1 1 foo1 bar1 10 2 1 foo2 bar2 10 3 NULL foo3 bar3 11 1 1 foo4 bar4 11 2 1 foo5 bar5 11 3 2 foo6 bar6 The pair(sclass_id, subj_id) must be UNIQUE. prof_id might be NULL. CREATE TABLE Professor ( id int PRIMARY KEY AUTO_INCREMENT, name varchar(100) NOT NULL ); CREATE TABLE Subject ( id int PRIMARY KEY AUTO_INCREMENT, name varchar(100) NOT NULL ); CREATE TABLE ProfessorsSubject ( prof_id int, subj_id int, PRIMARY KEY (prof_id, subj_id), FOREIGN KEY (prof_id) REFERENCES Professor(id), FOREIGN KEY (subj_id) REFERENCES Subject(id) ); CREATE TABLE StudentClass ( id int PRIMARY KEY AUTO_INCREMENT, name varchar(100) NOT NULL, building varchar(100) ); CREATE TABLE A ( sclass_id int, subj_id int, prof_id int, foo varchar(10), bar varchar(10), PRIMARY KEY (sclass_id, subj_id), FOREIGN KEY (sclass_id) … -
How to trigger a python script on the server through user action in react (Django+React)?
I'm trying to launch a python script on the backend when a user enters some numbers into a form using react. I have Django as the main "shell" for my app handling the backend and is pointing to React properly for the frontend. The idea is to run all complex mathematical models, big data processing, and calculations on Python in the backend while node.js is used to run only front-end UI related scripts. Django for substance, React for the aesthetics. I am able to use SpawnSync child_process in Node.jus to successfully execute when I type "node run_python.js" in the command line ("run_python.js" is the name of my function). But when I run "npm run dev", that's when node is saying it can't find child_process. I checked node_modules and the childprocess library is there with keywords "child_process" included in the pacakge.json. I also tried referencing "child_process" in the main package.json file as a dependency. Is there a better way to trigger a python script on the server through action in react? -
Accessing session data from websocket consumer in Django
I save task_ids as a session variable in a view: request.session['task_ids'] = task_ids and I want to access that data in the websocket consumer: import requests class ProcessConsumer(WebsocketConsumer): def connect(self): self.accept() session = requests.Session() task_ids = session.get('task_ids') // I guess I'm doing this wrong self.send(text_data = json.dumps({ 'task_ids': task_ids })) I get the following error: requests.exceptions.MissingSchema: Invalid URL 'task_ids': No scheme supplied. Perhaps you meant http://task_ids? How can I access session data from websocket consumer in a proper way? Thanks. -
How to get the value from a template in Django to pass it to another template?
I have a template which only lists records, and I have another template to show each record's details. I use function views. My list template's some parts are as shown below; ` {% if list.item_name == 'A' %} <a type="button" class="btn btn-info" role="button" target="_blank" href="{% url 'app_name:template_01' %}">View</a> {% elif list.item_name == 'B' %} <a type="button" class="btn btn-info" role="button" target="_blank" href="{% url 'app_name:template_02' %}">View</a> {% elif list.item_name == 'C' %} <a type="button" class="btn btn-info" role="button" target="_blank" href="{% url 'app_name:template_03' %}">View</a> {% else %} <a type="button" class="btn btn-info" role="button" target="_blank" href="{% url 'app_name:template_04' %}">View</a> {% endif %} ` What I am trying to achieve is that when one of the above options is selected, I want to display the item_name in the detail template like this; <h1>{{ list.item_name }}</h1> So, if it worked, it would be A, B, C, or the item name which comes from the else option. I tried using function views for this purpose. My function views are like the ones shown below; ` def List_FunctionView(request): context = {} context["list"] = some_model.objects.all() Detail_FunctionView(request, context) template_name = "app_name/list.html" return render(request, template_name, context) ` def Detail_FunctionView(request, context): selected_item = request.GET.get('list.item_name') context2 = context template_name = "app_name/template_04.html" return render(request, template_name, context2) … -
How to make little search in Django
I want to make search function in my project, with Model Agreements from django.db import models class Agreements(models.Model): username = models.CharField(max_length=128) # this i want to use to search email = models.CharField(max_length=128, unique=True) phone_number = models.CharField(max_length=128, unique=True) creation_date = models.DateField() conclusion_date = models.DateField() def __str__(self): return str(self.username) views.py from django.shortcuts import render from django.views.generic import ListView from django.db.models import Q from connections.models import Agreements, Connections def index(request): context = { 'index': Agreements.objects.all(), 'HM': Connections.objects.all(), } return render(request, 'list_agreements.html', context) class Search(ListView): template_name = 'list_agreements.html' context_object_name = 'Agreements' def get_queryset(self): return Agreements.objects.filter(username__icontains=self.request.GET.get('q')) def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['q'] = self.request.GET.get('q') return context my urls.py from django.contrib import admin from django.urls import path from connections.views import index, Search urlpatterns = [ path('admin/', admin.site.urls), path('', index, name='index'), path('search/', Search.as_view(), name='search'), ] [enter image descrienter image description hereption here](https://i.stack.imgur.com/gClVN.png) my list_agreements.html (only important parts) <form class="d-flex" role="search" action="{% url 'search' %} " method="get"> <input class="form-control me-2" type="search" type="text" placeholder="Search" aria-label="Search" name="q"> <button class="btn btn-outline-success" type="submit">Search</button> </form> </div> </div> </nav> <div class="limiter"> <div class="container-table100"> <div class="wrap-table100"> <div class="table100 ver1"> <div class="table100-firstcol"> </tbody> </table> </div> <div class="wrap-table100-nextcols js-pscroll"> <div class="table100-nextcols"> <table> <thead> <tr class="row100 head"> <th class="cell100 column2">ФИО</th> <th class="cell100 column3">Почта</th> <th class="cell100 … -
Does chaining prefetch_related fetch all sub-queries?
Take this for example: user = User.objects.prefetch_related("foo__bar__baz").get(id=id) In this scenario, do I not need to do: user = User.objects.prefetch_related("foo__bar").get(id=id) if I want to access values on bar, or if they are mixed between select_related and prefetch_related due to some being OneToOne and others being FK like this below? user = User.objects.prefetch_related("foo__bar__baz").select_related("foo_bar_baz_qux").get(id=id) Or would skipping the prefetch and only using select be sufficient? user = User.objects.select_related("foo_bar_baz_qux").get(id=id) -
Using prefetch_related / select_related on a GenericForeignKey's own related reverse fields
Is it possible to prefetch a GenericForeignKey that is attached to another GenericForeignKey? For example, the following is not possible (though I'd like it to be): Consider the imaginary model below. Homes are generic and can be attached to many different types of objects via the content_object field as usual. I'd like to do something like prefetch a user, along with their animals, and the animals homes (though I'm aware this below won't work): User.objects.prefetch_related("animals", "animals__home") Is there any way to achieve this? from django.contrib.contenttypes import generic from django.contrib.contenttypes.models import ContentType from django.db import models class User(models.Model): ... class Animal(models.Model): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') user = models.ForeignKey(User, related_name="animals") ... class Home(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.UUIDField() content_object = GenericForeignKey("content_type", "object_id") ... -
Deployment crashing on Railway
I keep trying to deploy my django app using railway. The app will build, but the deployment keeps crashing. This is the error I am getting: Fatal Python error: init_sys_streams: is a directory, cannot continue I have made sure that my Profile had the correct application name include, that did not solve my problem -
How can I show a form by pressing a button in python (using Django framework and Json file)?
I am working on a project in which I should show a form created from a Json file. I am beginner in programming, I try to explain it well. There is a Django app which makes the specific form from a Json file by Json editor. Currently the form can be shown by using an tag in HTML but I want to have a button and by clicking a button, the form be created. Here is the code in HTML: {% for test in tests %} <a href="{{test}}">test</a> {% endfor %} In forms.py, I have a class for creating a form from Json files. I want to have a small form, by taking two values and pressing a button then it shows a form created by the Django app (from Json file) and then I want to access the items of the form. -
Django App Issue with ColumnName changed to lower case in the postgres DB
I have a working Django app with Postgres DB in the backend. However the coulmn names are updated and switched to lowercase name in backend database, for eg: Earlier columnName was AccountName, now changed to accountname all lowercase. This cases the app to break since the model refers to the oldName. I tried changing to the Model to the lowercase name but it breaks at different places like DataFrame name and have to make lot of changes to make it work. class AccountStatus(models.Model): AccountNumber = models.CharField(max_length=255, null=True) AccountName = models.CharField(max_length=255, null=True) is there any simple solution to this issue, maybe using some alias or any parameter to pass etc? Thanks for the help. Tried this : class AccountStatus(models.Model): accountnumber = models.CharField(max_length=255, null=True) accountname = models.CharField(max_length=255, null=True) This results in cascade of changes in Filters, DataFrame key names etc and many other places. I am trying to figure out an easy solution for this? -
By default, is transaction used in Django Admin Actions?
I know that by default, transaction is used in Django Admin when adding, changing and deleting data according to my tests. But, I selected Delete selected persons and clicked on Go in Django Admin Actions. *I use PostgreSQL: Then, clicked on Yes, I'm sure to delete data: Now, only one query DELETE is run without including one or more other queries between BEGIN and COMMIT as shown below so I doubt that by default, transaction is used in Django Admin Actions. *These below are the PostgreSQL query logs and you can check how to log PostgreSQL queries : So by default, is transaction used in Django Admin Actions? -
How to setup guicorn command to start django q
Hello i have my app uploaded on digitalocean server. Whenever i upload it i use gunicorn command to start my app. Currently it looks like this: gunicorn reservationSystem.wsgi:application --bind 0.0.0.0:8080 --worker-tmp-dir /dev/shm My question is how to update it to start django-q service as well. I think this may be cause for my app to crash. After last update (it included django-q for the first time) it crashes whenever i try to open it. Because of that i suspect that the reason for app crashing is that django-q is not started. Just in case you notice something wrong here is my q_cluster setup: Q_CLUSTER = { 'orm': 'default', # should use django's ORM and database as a broker. 'workers': 4, 'timeout': 30, 'retry': 60, 'queue_limit': 50, 'bulk': 10, } Thanks for help -
Working on a django proyect, started using class views and getting TemplateDoesNotExist for the deleteView
enter image description here URLS.py urlpatterns = [ path('',views.ProductList.as_view(), name="products-page"), path('product/<int:pk>', views.SingleProductView.as_view(), name='product-detail-page'), path('product-add', views.ProductAddView.as_view(), name='product-add'), **path('delete/<int:pk>/', views.ProductDeleteView.as_view(), name='product-delete'),** path('update/<int:pk>/', views.ProductUpdateView.as_view(), name='product-update'), VIEWS.py class ProductDeleteView(DeleteView): model = Product template_name = "product/product_delete" success_url = reverse_lazy('products-page') context_object_name = 'product' HTML (Where delete link exists) {% for product in products %} <div class="col"> <div class="card mt-3" style="width: 18rem;"> <div class="card-body"> <h6 class="card-title text-wrap" >{{product.name}}</h6> <h6 class="card-subtitle mb-2 text-muted">{{product.description}}</h6> <h6 class="card-text">Costo: ${{product.cost}}</h6> <a href="{{ product.get_absolute_url }}" class="card-link">Edit</a> <a href="{%url "product-delete" product.pk%}" class="card-link">Delete</a> </div> </div> </div> {% endfor %} Delete HTML <form method="POST" class="row g-3"> <div class="col-auto"> <h6>Are you sure you want to delete {{product.name}}?:</h6> {% csrf_token %} <button type="submit" class="btn btn-danger mb-3" value="Delete">Delete</button> <button class="btn btn-primary mb-3">Cancel</button> </div> </form> Seems simple enough, all I want is to delete that entry from the database. -
Strawberry with social_django
How can i use social_django wih strawberry graphql? With graphene i be inherited my strawberry.type from SocialAuthJWT i used in grapgene like this. class SocialAuth(graphql_social_auth.SocialAuthJWT): user = graphene.Field(UserType) @classmethod def resolve(cls, root, info, social, **kwargs): social.user.is_verified = True social.user.save() token = get_token(social.user) return cls(user=social.user, token=token) I`d like login with google . -
Django access current user fields from derived class?
I have an extended User class, and then a Patient class inherited from it. After the patient logs in I can get first name using request.user.first_name but how can I get the value of address? models.py: class User(AbstractUser): username = None email = models.EmailField(unique=True) is_Patient = models.BooleanField(default=False) USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = ['password'] object = UserManager() class Patient(User): address = models.CharField(max_length=200) class Meta: verbose_name_plural = 'Patients' def __str__(self): return self.first_name + " " + self.last_name -
How to run django app on windows server ec2 instance with mysql database and costum domain
I have Copied my files to the server and also setup the domain in the route 53 and also installed the xampp server now When i try starting the server with the command Python manage.py runserver 0.0.0.0:80 it gives me the following error Error: [WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions but when i visit the domain it autmatically redirected to domian.com/dashboard/ and there is all the xampp and apache etc stuff i tried to run it with out specifying the ip and port the it redirects to the domian/dashboard i want this to use the xampp server for mysql and run on the domain -
Django tests, how to mock function
I try to mock function, but it is still called. Definitely, I'm doing something wrong. test.py from unittest import mock from rest_framework.test import APITestCase class WalletTest(APITestCase): @mock.patch("apps.some_app.utils.wallets.get_wallet_balance", {"on_hold_balance": 0, "balance": 1000}) def test_delay_payout_with_topup(self): PaymentService().check() apps.some_app.service.py from apps.some_app.utils.wallets import get_wallet_balance class PaymentService: def check(self, *args, **options): data = get_wallet_balance(wallet_id) apps.some_app.utils.wallets.py def get_wallet_balance_data(wallet_id): # some API call is made When I trigger Django tests, API call is still made, instead of using {"on_hold_balance": 0, "balance": 1000} dict What I want, is WalletTest use dict and not go into get_wallet_balance_data func and make API call. How to achieve that? -
What are best practices for adding initial configuration data to a Python Django instance?
I have a Django application that has a Setting model. I've manually added the configuration data to the database through the Django Admin UI/Django Console but I want to package up this data and have it automatically created when an individual creates/upgrades an instance of this app. What are some of the best ways to accomplish this? I have already looked at: Django Migrations Topics Documentation which includes a section on Data Migrations shows a data migration but it involves data already existing in a database being updated, not new data being added. Django Migration Operations Reference show examples using RunSQL and RunPython but both only when adding a minimal amount of data. How to create database migrations looks at moving data between apps. How to provide initial data for models mentions data migrations covered in the previous docs and providing data with fixtures. Still I haven't found one that seems to line up well with the use case I'm describing. I also looked at several StackOverflow Q&As on the topic, but all of these are quite old and may not cover any improvements that occurred in the last 8+ years: Programmatically using Django's loaddata How can I provide the … -
server shows "page not found-404" error while verifying password
I am trying to create a password verification project but when I try to run that, it keeps getting 404 error while it should be redirect on my login page or password do not match error. Although i get the verification email and get the link, when i click the link and try to reset my password, this error comes Not Found: /change-password/263d4b70-c6db-4341-9b56-924d3c9000e6/change-password/263d4b70-c6db-4341-9b56-924d3c9000e6/ can anyone tell me what I am missing here? It would be very helpful Here's a snippet of my code, thanks in advance urls.py from django.urls import path from .views import * urlpatterns = [ path('', home, name='home' ), path('login/', login_attempt, name='login' ), path('register',register_attempt, name='register'), path('logout_user', logout_attempt, name='logout_user'), path('forgetpassword', forgetPassword, name='forgetpassword'), path('change-password/<token>/', changePassword, name='changepassword'), ] views.py from django.shortcuts import render,redirect from django.contrib.auth import authenticate from django.contrib import auth from django.contrib import messages from django.contrib.auth.decorators import login_required from epayapp.helpers import send_forget_password_mail from .models import * import uuid # Create your views here. def forgetPassword(request): try: if request.method == 'POST': username= request.POST.get('username') curr_user= User.objects.filter(username= username).first() if curr_user is None: messages.success(request, 'Username not found') return redirect('forgetpassword') user_obj= User.objects.get(username=username) token= str(uuid.uuid4()) user_obj.forget_password_token= token user_obj.save() send_forget_password_mail(user_obj, token) messages.success(request, 'An email is sent') return redirect('forgetpassword') except Exception as e: print(e) return render(request, 'index/forget_password.html') …