Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Saving Javascript changes using django
I am rendering element using javascript. How can I save itvto my website using django. I am a beginner in django can someone guide how to do this -
How can i convert following query in django rest framework
SELECT id,ewbno,ewbdate,gengstin,(select code from mt_business_partner where gstin=t00.gengstin limit 1) code, (select name from mt_business_partner where gstin=t00.gengstin limit 1) name from mt_ewb_master t00 where ewbno like ? order by id limit 50") i want to convert this and write it in django ORM -
Unsupported lookup 'category' for CharField or join on the field not permitted
models.py from django.db import models from django.urls import reverse class Category(models.Model): category_id = models.AutoField category_name = models.CharField(max_length=50, default="") desc = models.CharField(max_length=1000) slug = models.SlugField(max_length=20) image = models.ImageField(upload_to='onlinePizza/images', default="") def get_url(self): return reverse('category', args=[self.slug]) def __str__(self): return self.category_name class Product(models.Model): product_id = models.AutoField product= models.CharField(max_length=50) category = models.ForeignKey(Category, default='', null=True, on_delete=models.CASCADE) desc = models.CharField(max_length=1000) image = models.ImageField(upload_to='onlinePizza/image', default="") def __str__(self): return self.product This is my views.py file. I show error at bestseller = Product.objects.filter(product__category__icontains='BestSeller') views.py from django.shortcuts import render from . models import Category, Product, Deal from math import ceil def index(request): bestseller = Product.objects.filter(product__category__icontains='BestSeller') context = {'bestseller':bestseller} return render(request, 'onlinePizza/index.html', context) I want to Bestseller category product at index.html I use Django 4 and pyhton 3.9 -
Django queue reincarnated monitor Process-1:228 after sudden death
I've installed and configured Django-Q 1.0.2 (on Django 1.11.10 with Redis 1.0.1 and Python 3.6.9). This is my Cluster configuration: Q_CLUSTER = { 'bulk': 5, 'recycle': 500, 'compress': True, 'save_limit': 500, 'queue_limit': 500, 'label': 'Django Q', 'attempt_count': 1 } -
django makemessages can't translate all words
makemessages can't detect all translation words... I tried all but it didn't work. My command django-admin makemessages --all --ignore=venv # and python manage.py makemessages --all --ignore=venv My template {% load i18n %} {% trans 'тестовый какой-то текст' %} {% trans 'Республика Узбекистан, г.Ташкент, Шайхонтохурский район, улица Лайлитогон 1, 141300, Самаркандская область, Пайарикский район, улица Самарканд 52.' %} makemessages detected first text but not second... Pls help -
Properly rename column name using display decorator in Django admin.py panel
I'm trying to rename the IS STAFF to STAFF STATUS here: I'm just wondering if it's possible to rename it from admin.py & NOT use the verbose_name inside the model. I wrote this code in admin.py: @admin.register(User) class CustomUserAdmin(DefaultUserAdmin): list_display = [ 'username', 'RENAMED_EMAIL', 'first_name', 'last_name', 'RENAMED_STAFF', 'is_active', ] @admin.display(description="EMAIL ADDRESS", ordering='-email') def RENAMED_EMAIL(self, obj): return obj.email @admin.display( description="STAFF STATUS", boolean=True, ordering='-is_staff', ) def RENAMED_STAFF(self, obj): return obj.is_staff list_editable = ['is_staff', 'is_active'] The EMAIL ADDRESS was renamed successfully but as I used is_staff in list_editable, I get this error: ERRORS: <class 'accounts.admin.CustomUserAdmin'>: (admin.E122) The value of 'list_editable[0]' refers to 'is_staff', which is not contained in 'list_display'. Tried to use RENAMED_STAFF inside list_editable too, it results in another error: ERRORS: <class 'accounts.admin.CustomUserAdmin'>: (admin.E121) The value of 'list_editable[0]' refers to 'RENAMED_STAFF', which is not a field of 'accounts.User'. What is the proper way to customize those column names? -
Django + uvicorn poor performance
I'm testing Django asgi performance using two very simple views. I'm running gunicorn and uvicorn in such a manner: gunicorn core.wsgi --workers=1 --threads=1 --access-logfile=- core.wsgi:application uvicorn --workers 1 core.asgi:application The views are as follows: def simple_sync_view(request): usernames = "Hello World" return JsonResponse({'message': usernames}) async def simple_async_view(request): usernames = "Hello World" return JsonResponse({'message': usernames}) Project has no middlewares enabled. When testing using : wrk -t10 -c100 -d10s http://127.0.0.1:8000/test/sync/ synchronous server is always several times faster: 10 threads and 100 connections Thread Stats Avg Stdev Max +/- Stdev Latency 37.42ms 7.87ms 158.35ms 98.88% Req/Sec 271.54 38.28 303.00 79.60% 26885 requests in 10.01s, 4.87MB read Requests/sec: 2685.95 Transfer/sec: 498.40KB comparing to uvicorn: 10 threads and 100 connections Thread Stats Avg Stdev Max +/- Stdev Latency 115.38ms 37.55ms 245.49ms 53.91% Req/Sec 88.65 41.14 200.00 74.63% 8638 requests in 10.02s, 1.40MB read Requests/sec: 862.49 Transfer/sec: 143.19KB regardless of type of view, sync or async. So I wonder, is the Django in asgi mode so slow or what ? -
How hard can it be? Django ImageField
After struggling for some time to find answer(not a single answer funcioned for me) i decided to ask a question- What are correct steps to Display Image uploaded via Django Admin, to my custom template (html page) in DJANGO 4? -
How to get proper json data from irregular json in phpmyadmin (Mysql)?
`a:1:{i:0;a:6:{s:19:"purchase_product_id";s:2:"44";s:16:"purchase_product";s:27:"Sumo Xtra Emulsion - Base 4";s:4:"type";s:17:"Exterior Emulsion";s:13:"product_range";s:1:"2";s:13:"price_per_qty";s:0:"";s:3:"qty";s:3:"200";}}` The above is the data stored in MySQL db. Here I want to extract this data into proper JSON and use this Django. -
Change URL of browsable API of django rest framework from 127.0.0.1:8000 to 127.0.0.1:8000/api
I followed the simple quickstart tutorial in the official documentation of django rest framework. https://www.django-rest-framework.org/tutorial/quickstart/ The tutorial works fine. The URL of the browsable API is at 127.0.0.1:8000. How do I change it to 127.0.0.1:8000/api? The code for urls.py; from django.urls import include, path from rest_framework import routers from tutorial.quickstart import views router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) router.register(r'groups', views.GroupViewSet) # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ path('', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] I am using django v4, python v3.9 -
How to fill the remaining database fields at the server in django
I am new to django and I am creating API endpoints using django rest framework. I have created a post request so a user will fill the request body which is in json and that json will be added to the database table however the twist is that the user has to fill only a few fields and the remaining fields will be added at the server end. For eg. lets say that the database table has fields room_number, check_in, check_out, date, capacity. The user will only fill fields check_in, check_out, date and the remaining fields will be filled at the server end. So can someone please tell me how can I do it? -
iterate over forms in Django formset
I have a formset where I am trying to iterate over related_component so it shows dynamically all components that are related to this product. For now, I managed to count the number of components but it selects me in all forms always the first choice from the database. What I want is to show the components that are related only to this product and show all of them, not only the first component from the list so the user doesn't need to select it manually. Do I need to overwrite init method in the form or I can do it somehow in ProductDetailView? I'd appreciate any help. Here is what I have now: This is something I want to see: forms.py class CalculatorFormProduct(forms.ModelForm): author = forms.CharField(required = False) number_of_units = forms.IntegerField(help_text='Only numeric values are allowed.', min_value=0) total_price = forms.IntegerField(widget = forms.HiddenInput(), required = False) created = forms.DateTimeField(required = False) class Meta: model = CERequest fields = ('author', 'created', 'related_product', 'related_component', 'number_of_units', 'total_price') CalculatorFormsetProduct = formset_factory(CalculatorFormProduct, extra=0) views.py class ProductDetailView(FormMixin, DetailView): template_name = 'hubble/ProductDetailView.html' model = Product form_class = CalculatorFormsetProduct def get_context_data(self, **kwargs): context = super(ProductDetailView, self).get_context_data(**kwargs) get_components = CostCalculator.objects.filter(related_product__slug=self.kwargs['slug']) formset = CalculatorFormsetProduct(initial=[{ 'author': self.request.user.email, 'related_product': self.object, 'related_component': self.object, # what … -
When Django Model creates, can I define fields in __init__?
Are they typed in below same? The first code which defines fields in class attribute section is recommended by django documents class Musician(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) instrument = models.CharField(max_length=100) The second code which I want to use defines fields in init function. class Musician(models.Model): def __init__(self, *args, **kwargs): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) instrument = models.CharField(max_length=100) super().__init__(*args, **kwargs) I want to use second codes when I define classmethod in Model to define functions validateing fields like below. class HyperLinks(model.Model): def __init__(self, *args, **kwargs): self.links = models.JSONField(default=[], validators=[self.validate_links]) super().__init__(*args, **kwargs) @staticmethod def validate_links(data): pass -
Add posts on the frontend in real time Django
I am looking for a way to add real-time posts to my Django blog. I would like to use a way to make them appear on the database as soon as I insert them, without refresh and without a setInterval or the like. Some idea? -
how to do Django query that is ordered by latlng string
Current Situation I Am fetching data that contains Strings that represent the Latlng of some locations .. like 30.78829892811801,31.2769004988329 30.78848118485095,31.27649189363398 30.78869531217787,31.27615745128788 etc. What I have tried now I am doing Django query like ModelName.objects.all().order_by('latlng') but it is not ordering it as the field is simply a Charfield .. also converting it to double is not working as it contains 2 different double separated by the comma. What I need to do Is there a way to convert this string to LatLng that is orderable by location or something like this? -
Update Django Model m2m field, based on update of another m2m field
I got the following model: class Role(models.Model): name = models.CharField(max_length=20) groups = models.ManyToManyField( Group, blank=True ) users = models.ManyToManyField( User, blank=True ) and I have developed the following signal: @receiver(m2m_changed, sender=Role.groups.through) def sync_groups_and_users_assignment(sender, instance, action, **kwargs): Group = kwargs["model"] users = [] # Find users that belong in the groups that have been moved in the group m2m field for pk in kwargs["pk_set"]: moved_group = Group.objects.filter(pk=pk) related_users = User.objects.filter(groups__in=moved_group) for user in related_users: users.append(user) # Move those users accordingly for user in users: if action == "post_add": instance.users_assignment.add(user) if action == "post_remove": instance.users_assignment.remove(user) instance.save() When I set the users field to read only in admin.py the signal works as expected. The users that belong to group are moved, when the group is moved. class RoleAdmin(VersionAdmin): filter_horizontal = ('groups', 'users', ) readonly_fields = ('users_assignment',) However if I remove the readonly_fields = ('users_assignment',) the functionality breaks. I guess this happens because on model.save() django overrides the values of the field after the m2m signal function changes them, resulting to rolling them back to the UI values. Is there any way to tell django that if the groups m2m field has been changed, then don't save the users UI m2m field values? -
Django overriding default managers of contrib models
I have a Django app named site_settings in which SiteSettings model is defined. This model contains a foreign key to django.contrib.sites.models.Site model. Now I want to override default objects manager of Site model with new one I defined: from django.contrib.sites.models import SiteManager as _OrigSiteManager class SiteManager(_OrigSiteManager): ... I tried: Site.add_to_class("objects", SiteManager()) But it didn't work. The problem is I am adding to class with already existing objects name. When adding with another name, it works as expected: Site.add_to_class("my_objects", SiteManager()) # now Site.my_objects points to my custom manager But I want to override existing objects manager with my custom manager. How can I do that? -
django.db.utils.DataError: value too long for type character varying(50)
I have a signup form on my Django app deployed on Heroku. It is working fine except for one thing. When I try to add new data to the database by getting the data from my signup form, it does not add the data. In the logs of my Heroku, it shows this: django.db.utils.DataError: value too long for type character varying(50) From this, what I understand is that any of my model's fields has a 50 max length and I'm giving the data more than that limit. --might be possible But when I changed the max length from 50 to 150, and tried to migrate the changes in Heroku using heroku run python manage.py migrate after making the migrations using makemigrations mehtod, it shows the following error in the console: File "/app/manage.py", line 22, in <module> main() File "/app/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 460, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 98, in wrapped res = handle_func(*args, **kwargs) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/commands/migrate.py", line 290, in handle post_migrate_state = executor.migrate( File "/app/.heroku/python/lib/python3.10/site-packages/django/db/migrations/executor.py", line 131, in … -
Query M2M relations in Django
I've the following model: class Quiz(models.Model): name = models.CharField(max_length=255) month = models.DateField() class Question(models.Model): title = models.CharField(max_lenght=255) category = models.CharField(max_length=255) status = models.CharField(max_length=255, status=(('Pending', 'Pending'), ('Approved', 'Approved')) class Contest(models.Model): quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE) questions = models.ManyToManyField(Question, related_name='contest_questions') Now I want to get list of quizes with all questions whose status=Pending? Any help would be much appreciated! -
Cannot login to django admin by a created staff
I hope you are fine. I have created a superuser in my django project that access to all of the permissions of the admin page. The problem is that when I add an object to the customized user model and set is_staff = true for that new user and then logout from the admin, I cannot login with the staff user account due to the error that says “please enter correct username and password for the staff acount” despite the matter that the username and password of that staff user are right. I will thank if anyone help me to solve this problem -
No module named smtp in
[No module named smtp. Well I don't know what to do. I've been following COrey Schafer's Django Tutorial but I couldn't figure out the problem that arose at Email and Password reset module. ][I have used google app password and done everything exactly as instructed but somehow I can't figure out the problem.] -
DTL and Custom js not working together in Django
I have used multiple custom js in my project. It is working perfectly in simple HTML but when I tried to use that custom js in the Django DTL format for example {% for data in data %} 'custom js' {% endfor %} then it is not working and custom js is not loading. Can anyone help? I am stuck here for so long now. I am not able to find any solution regarding this -
I have makemigrations error, how can I solve it?
from turtle import mode File "/usr/lib/python3.8/turtle.py", line 107, in import tkinter as TK ModuleNotFoundError: No module named 'tkinter' -
What is the proper way to implementing the revoke token URL in FastAPI, Django, Flask?
I'm implementing the JWT in FastAPI, Which is proper way to revoke the access and refresh tokens? Single Logout URL to revoke the access and refresh Individual revoke URL? Thanks in advance -
How to use django rest framework to access form-data with multiple files with file name for each file separately?
Requirement: Upload multiple files with custom file name for each file Frontend: React I use django rest api and want to get each file with associate data like custom file name. But I don't have idea to how to do this. When I receive api request with form-data that only contains files then it is okay to access these data using request.FILES/request.data. It is also okay to receive single file with its' file name because in form data we can set one key(file) for file and another key(text) for file name. But how it is possible to use multiple files with file name for each file. Frontend is not designed/developed by me. So tried with curl/Postman to simulate the frontend request. But no idea about the real implementation of the backend and frontend. So no way to test this kind of request using Postman/Curl