Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Finding the highest amount of an instance in django models
I have two models that have a foreign key relationship to each other. One of the models is a Student and the other is Grade. The issue I'm having it I'm getting the values I want with model methods in the template. so what I'm trying to do is I want the Student with the highest grade score all the way to the lowest. How actually can I achieve this? -
QueryDict has list, but actualy show string
today I have encountered thing I do not really know why it happened. I POSTed request with form that had MultipleModelChoiceField, in frontend I selected multiple of them (id 2 and 3), then in debug in PyCharm I wanted to see my POST request and saw this [see image]. With form.POST.get("people") I got >>> "3" as a result. After sanitizing data with After I accessed form.cleaned_data, the result was good, but I don't quite understand why did it happen, can someone please, try to explain what happened and why? Thanks all! -
What path should I take erlang(elixir), node.js or django(python)
Please I am asking for and advice so that I can know what path to take because I am currently very confused as to which path to take. I want to build a project with very strong fault tolerance but must be very fast and offering real time result. I have been confused as to which path I should take amidst the 3 server side languages i.e. erlang, node.js or django. I have done some work in node.js and my hat off for it but the problem I have with node.js is when I make modification to the code, I have to restart the server thereby lossing session. That has made me sceptical of using nnode.js. I can't imagine all my users being logged out from the server when I make changes to my code. SO that makes me not use node.js Django on the other hand saves session that is running when I updates my code base, no session loss unlike node.js the only matter is when I restart the server any one logging into the server while it is restarting would not be able to enter but the session is still there. Also django's is learning curve was … -
How can i display svg (like an image) from a string in django template?
I want to display in a django template the content of a svg file retrieved from a database as a string. when I call the field of my model, django displays the content as a string, the svg is not interpreted as a schema. For example, my template displays <Element {http://www.w3.org/2000/svg}svg at 0x178ebe2dc80> or bla bla bla instead of a schema. I want to display a schema, not a string. How can I do that please? Thank you -
How to add token in response after registering user DRF Social OAuth2
I am using DRF Social OAuth2 for social authentication, it's giving me the token when I log in, but I want to return the token in response when I register a user with an email and password. How can I do that -
Django Websocket Send Text and bytes at sametime
I have client and server in my project. In the client part, the user will upload his own excel file and this file will come to my server for processing. My artificial intelligence python code will run on my server and it will make changes to excel. When every time it changes, I want to send the updated version to the client so that the client can see the change live. Example Let's say I have 10 functions on server side, each function changes some cells in excel(I can get the index of the changed cells). When each function is finished, I will send the changing indexes to the client and these changed places will be updated in the table in the client (C++, Qt). At first, I made the server with PHP, but calling my artificial intelligence python codes externally(shell_exec) was not a good method. That's why I want to do the server part with python. Is django the best way for me? What I've tried with Django: I wanted to send data continuously from server to client with StreamingHttpResponse object, but even though I used iter_content to recv the incoming data on the client, when all the code … -
How do I prevent my Django Database from being overwritten
Currently I have a Django application running on my personal website from PythonAnywhere.com. When I make updates to the site I login to PythonAnywhere and git pull to update my application. When I do this the data that was entered through the website since the last update gets lost from the database when I update. What can I do to overcome this? I am currently using the SqlLite version that comes preinstalled with the Django App. This likely could be part of the issue but need some help understanding how to overcome it. -
AUTH_USER_MODEL reference in settings.py Django
I have a installed an app called 'Login', who have a folder 'models' inside, with a custom_user model. The problem occurs when I tried to configure settings.py, specially auth_user_model. in installed apps I have the following: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'project_app.login' ] and below AUTH_USER_MODEL = 'login.models.CustomUser' But I have the following error: "Invalid model reference. String model references must be of the form 'app_label.ModelName'." I put the .models in AUTH_USER_MODEL, because I want to reference the app that the CustomUser is inside the folder "models" in Login. Also, I tried with declare like this: AUTH_USER_MODEL = 'login.CustomUser' but the error is this: 'AUTH_USER_MODEL refers to model 'login.CustomUser' that has not been installed' -
how install reportlab for django on dockerfile?
hi when i want install reportlab with pip on docker for django project, i have this error : Preparing metadata (setup.py): started Preparing metadata (setup.py): finished with status 'error' error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. image of error description -
How can I use `phone number` and `otp` in "django-rest-framework-simplejwt" instead of `username` and `password` to generate token?
#urls.py I just want to know how to set custom fields, for e.g instead of 'username' and 'password' can i get 'phone_number' and otp from django.urls import path from . import views from . import api_views from django.conf.urls.static import static from django.conf import settings from rest_framework_simplejwt.views import (TokenObtainPairView,TokenRefreshView,) urlpatterns = [ # Api Urls path('api/',api_views.getRoutes,name="api"), path('api/register',api_views.registerPatient,name="signup"), path('api/patient/',api_views.getPatients,name="patients"), path('api/create/',api_views.CreatePatient,name="create"), path('api/patient/<str:pk>/',api_views.getPatient,name="patient"), path('api/update/<str:pk>/',api_views.updatePatient,name="update"), path('api/delete/<str:pk>/',api_views.deletePatient,name="delete"), path('api/login/',TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('api/doctor/',api_views.doctorRegister,name="doctorreg"), path('api/getroutes/', api_views.getRoutes, name='getroutes'), path('api/sotp/',api_views.send_otp,name="sotp"), path('api/votp/',api_views.verify_otp,name="votp"), path('api/signup/',api_views.registerPatient,name="signup"), ]``` -
Specify a .env file in Django in command line or vscode launch.json
At the moment I have a Django project running in VS Code. This currently uses a single .env file to connect to a SQL Server database. environments/.env DATABASE_URL=mssql://USER_NAME:PASSWORD@SERVER_NAME/DATABASE_NAME settings.py import environ env = environ.Env( # set casting, default value DEBUG=(bool, False) ) BASE_DIR = Path(__file__).resolve().parent.parent ENVIRONMENT_DIR = os.path.join(BASE_DIR, "environments") environ.Env.read_env(os.path.join(ENVIRONMENT_DIR, '.env')) env = environ.Env() ... DATABASES = { "default": env.db_url(), } } __.vscode/launch.json This is ran in VS Code with the following launch configuration: { "version": "0.2.0", "configurations": [ { "name": "Python: Django", "type": "python", "request": "launch", "program": "${workspaceFolder}/manage.py", "args": [ "runserver", ], "django": true }, ] } Question The question is, is it possible to have a multitude of different environments to connect to using different multiple environment files? Something like: dev.env test.env prod.env Then get VS Code to run a specific .env from the launch.json. Sources: https://django-environ.readthedocs.io/ https://django-environ.readthedocs.io/en/latest/tips.html#multiple-env-files https://djangostars.com/blog/configuring-django-settings-best-practices/ -
General questions about Django and DRF
I've made a project using Django and Bootstrap (I plan to use React for the frontend). Then I started building REST API with DRF and it seems that my DRF views are pretty similar (if not duplicative) to my original Django views such as DetailView, UpdateView and etc.Now I wonder if I can keep my old views or should I completely replace them with DRF ones? Or should I use DRF views for CRUD and keep particular Django views? And another qusetion: am I right that when working with Django and DRF Django becomes just an ORM provider also responsible for business logic, authentication and some other features? Thanks. -
How do I display all commented TV and MOVIE SCORES in descending order?
What we want to achieve. I want to display the score (stars) of a movie in descending order. Present condition The tmdb API is used to retrieve movie information. And the model movie and TV have only ID and stars(score). From here, only those with stars are returned to html. I want to ask a question. And if score is selected, how can I make it appear in descending score order? data = requests.get (f "https://api.themoviedb.org/3/tv/{tv_id}?api_key={TMDB_API_KEY}&language=en-US"). Now you can get the information of tv. def index(request): sort_by = request.POST.get('sort_by','') tv = TV.objects.order_by(sort_by) movie = Movie.objects.order_by(sort_by) # Get the results from the API if tv: data_tv = requests.get(f"https://api.themoviedb.org/3/tv/{re.GET.get('id')}?api_key={TMDB_API_KEY}&language=en-US") if movie: data_movie = requests.get(f"https://api.themoviedb.org/3/movie/{movie.GET.get('id')}?api_key={TMDB_API_KEY}&language=en-US") # Render the template return render(request, 'Movie/index.html', { "data_tv": data_tv.json(), "data_movie": data_movie.json(), }) class Movie(models.Model): id = models.CharField(primary_key=True, editable=False, validators=[alphanumeric],max_length = 9999) stars = models.FloatField( blank=False, null=False, default=0, validators=[MinValueValidator(0.0), MaxValueValidator(10.0)] ) def get_comments(self): return Comment_movie.objects.filter(movie_id=self.id) def average_stars(self): comments = self.get_comments() n_comments = comments.count() if n_comments: self.stars = sum([comment.stars for comment in comments]) / n_comments else: self.stars = 0 return self.stars class TV(models.Model): id = models.CharField(primary_key=True, editable=False, validators=[alphanumeric],max_length = 9999) stars = models.FloatField( blank=False, null=False, default=0, validators=[MinValueValidator(0.0), MaxValueValidator(10.0)] ) def get_comments(self): return Comment_tv.objects.filter(tv_id=self.id) def average_stars(self): comments = self.get_comments() n_comments … -
How to receive/subscribe to mqtt request via django without external broker
I have owned a server based on djnago and i need to get mqtt messages from a device directly to my server without any external brokers. How to do this? I need only request response and there is no need of broadcasting. Since it is an iot application. What iam asking is is there any way to just collect a message and send back response using mqtt protocol ,or any method to create our own djnago based broker -
How to filter the django queryset based on the hours?
Serializer class MyModelSerializer(serailizers.ModelSerializer): hour = serializers.SerializerMethodField() def get_hour(self, obj): created_at = obj.created_at # datetime now = datetime.now() return (now - datetime).total_seconds() // 3600 class Meta: model = MyModel fields = "__all__" API In the api there will be a filter parameter hr. If it provided for e.g 4 then I should return only the matching entries which has hour 4(calculated in the above serializer). How can I do this ? @api_view(["GET"]) def get_list(request): qs = MyModel.objects.all() hr = request.GET.get("hr") if hr: qs = qs.filter(created_at__hour=hr) # get_hour value = hr this should be the comparison return MyModelSerializer(qs, many=True).data -
Why do I get an error when I try to add a new object?
I added a field that is a foreign key called user in a model but I initially received an error that said: It is impossible to add a non-nullable field 'user' to bid without specifying a default. So I made the default the string 'user'. However, instead I have been receiving the error: ValueError: invalid literal for int() with base 10: 'user' when I try to migrate the changes I have made (python3 manage.py migrate). And when I try to add a new bid, I get an error in the web page: OperationalError: no such column: auctions_listing.user_id How do I fix this? models.py: class Bid(models.Model): item = models.ForeignKey(Listing, on_delete=models.CASCADE) price = models.FloatField() user = models.ForeignKey(User, on_delete=models.CASCADE) -
Django Error: ValueError: Field 'id' expected a number but got 'Нет'
I was adding a new model, but had the error ValueError: Field 'id' expected a number but got 'Нет'. After that I deleted a new model, but error don't disappear. I tried to change models.py, admin.py, form.py and I even deleted fully models.py, but it didn't change anything. models.py without choices class Card(models.Model): name = models.CharField("Наименование постановления" ,max_length=200) date = models.DateField("Дата вынесения:", null=True, blank=True) case_number = models.CharField("Номер дела:", max_length=40, null=True, blank=True) documents = models.URLField("Связанные документы (ссылки):", max_length=300, blank=True, null=True) trial = models.CharField("Наименование суда", max_length=37, choices=TRIALS, blank=True, null=True) instance = models.CharField("Инстанция:", max_length=12, choices=INSTANCE_CHOICES, blank=True, null=True) intial = models.CharField("Первоначальное решение первой инстанции", choices=REQUIREMENTS, blank=True, null=True, max_length=200) counter = models.CharField("Встречное решение первой инстанции", choices=REQUIREMENTS,blank=True, null=True, max_length=200) appellate = models.CharField("Решение апелляционной инстанции", choices=CHOICES, blank=True, null=True, max_length=200) cassation = models.CharField("Решение кассационной инстанции", choices=CHOICES,blank=True, null=True, max_length=200) proceeding = models.CharField("Вид судопроизводства:", max_length=16, choices=PROCEEDING_CHOICES, blank=True, null=True) first_dispute = models.CharField("Категория спора (подкатегория 1)", max_length=122, choices=FIRST_DISPUTE, blank=True, null=True) second1_dispute = models.CharField("Категория спора (подкатегория 2-1)", max_length=122, choices=SECOND1_DISPUTE, blank=True, null=True) second2_dispute = models.CharField("Категория спора (подкатегория 2-2)", max_length=122, choices=SECOND2_DISPUTE, blank=True, null=True) third_dispute = models.CharField("Категория спора (подкатегория 3)", max_length=122, choices=THIRD_DISPUTE, blank=True, null=True) review = models.CharField("История рассмотрения:", max_length=4, choices=YES_OR_NO_CHOICES, blank=True, null=True) original_claim = models.CharField("Первоначальное требование:", max_length=300, blank=True, null=True) counter_claim = models.CharField("Встречное требование:", max_length=300, blank=True, null=True) … -
How solve django-admin is not recognized...?
I'm trying: Django-admin startproject myweb This is what i see: 'django-admin' is not recognized as the name of a cmdlet, function, script file, or operable Even i added python27/Scripts to my pc environment variables but didn't work -
Is there any advantage or disadvantage to using reverse accessors vs direct queries?
I happen to be working on an existing project, that uses a lot of direct queries instead of reverse accessors. Take the following contrived example: class Student(Model): name = CharField(...) school = ForeignKey(School, ...) class School(Model): def get_daves(self): ... The 'get_daves' method on School could be implement in either of the following ways: def get_daves(self): return self.student_set.filter(name='Dave') def get_daves(self): return Student.objects.filter(school=self, name='Dave') And the project I'm working on, seems to have a lot of the latter, whereas I'd typically use the first option. Aside from being more succinct, and arguably clearer as to what you're intending, are there any other reasons to use the reverse accessor method, over querying the Students directly. I assume under the hood they result in equivalent DB queries, and the same amount of work constructing the models when the queryset is iterated. I just wanted to make sure there isn't a good reason to go ahead and start changing all of the instances of the direct queries in the project as I find them. -
I want to split name with space and tag_name with underscore. How can I split through jinja templating
Html file: {% for i in i|split:' ' %} <tr> <td> <p>{{ i }}</p> </td> <td> <p>{{ j }}</p> </td> </tr> {% endfor %} custom_tags.py from django import template register = template.Library() @register.filter(name='split') def split(obj, sub_strings): list1 = obj.name.split(" ") list2 = obj.tag_name.split("_") if "" in list1: list1.remove("") return [list1, list2] -
Why Does Djongo Gives Error While EveryThink Is OK? database is connected
i dont know why. but it works well on local pc and i putted it on CPanel its connected to database. but when i load a page. it gives dbError: this code works in localhost ( on my pc ) but when i uploaded it on cpanel it gives error ;/ ( db is on cpanel ) DBCode: The DBName and username and password is currect DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': '(db names are currect)', 'ENFORCE_SCHEMA': False, 'CLIENT': { 'host': 'mongodb://(entered username):(entered password)@localhost:27017/( iwrote db name)' } } } i got putted __in and [ ] cuz i heared that djongo needs booleans to be like this And Views.Py stores = Store.objects.filter(Premium__in=[True]) return render(request, 'base/home.html', context={'stores': stores}) Request Method: GET Request URL: https://www.storefa.xyz/home/ Django Version: 4.0.6 Python Version: 3.9.12 Installed Applications: ['captcha', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'base.apps.BaseConfig'] Installed Middleware: ['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'] Template error: In template /home/storefax/StoreFa/base/templates/base/home.html, error at line 72 (Could not get exception message) 62 : </div> 63 : <br> 64 : <br> 65 : <br> 66 : <br> 67 : <div class="about-container"> 68 : <div class="kh kh-1"></div> 69 : <div class="kh kh-2"></div> 70 : <div class="kh kh-3"></div> 71 … -
Trying to hold Cart ID and product quantity through JQuery but its returning unidentified value
This is my HTML code <div class="col-sm-2 product_data1 border-left"> {% csrf_token %} <input type="hidden" class="product_id1" value={{ item.id }}> <select class="changeStatus" value={{ item.product_quantity }} name="quantity"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> </select> And this is my JQuery var cart_id = $(this).closest('.product_data1').find('.product_id1').val(); var product_quantity = $(this).closest('.product_data1').find('.changeStatus').val(); var token = $('input[name=csrfmiddlewaretoken]').val(); -
Background tasks with Django on Heroku
So I'm building a Django app on Heroku. The tasks that the app performs frequently run longer than 30 seconds, and therefore I'm running into the 30s timeout by Heroku. I first tried solving it by submitting the task from my Django view to AWS lambda, but in that case, the view is waiting for the AWS Lambda function to finish, so it doesn't solve my problem. I have already read the tutorials on Heroku on handling background tasks with Django. I'm now faced with a few different options on how to proceed, and would love to get outside input on which one makes the most sense: Use Celery & Redis to manage the background tasks, and let the tasks be executed on AWS Lambda. Use Celery & Redis to manage the background tasks, but let the tasks be executed in a Python script on Heroku. Trying to solve it with asyncio in order to keep it leaner (not sure whether that specific case could be solved with asyncio, though? Maybe there's an even better solution that I don't see? Looking forward to any input/suggestions! -
Django Google Spreadsheet backup
I want to backup my data to Google Spreadsheet in Django project. I will get an access token shared by google from front-end (mobile app and web app - both). Now I need to, authenticate to google drive using that access token after that get list of the file in google drive if my required file exist then get that file if my required file doesn't exist then create an file and get that write backup data in spreadsheet close Now step by step I want to do this. I need exact solution, I studied google drive, google spreadsheet API documentation for Python. But that is not working for me. I need to implement this in Django. -
Sub Category Name not coming despite the if condition coming as True
I am aware that I have asked this question before but I am really struggling and unable to solve this question I have made product CRUD using serializers and foreign keys and I am making a dynamic page with categories and subcategories. The issue is that despite the if condition passing the sub categories are not getting printed only category_name is there as shown below models: class Products(models.Model): categories = models.ForeignKey(Category,on_delete=models.CASCADE) sub_categories = models.ForeignKey(SUBCategories,on_delete=models.CASCADE) color = models.ForeignKey(Colors,on_delete=models.CASCADE) size = models.ForeignKey(Size,on_delete=models.CASCADE) image = models.ImageField(upload_to = 'media/',width_field=None,height_field=None,null=True) title = models.CharField(max_length=70) price = models.CharField(max_length=10) sku_number = models.CharField(max_length=10) product_details = models.CharField(max_length=1000) quantity = models.IntegerField(default=0) isactive = models.BooleanField(default=True) class Category(models.Model): #made changes to category_name for null and blank category_name = models.CharField(max_length=30) category_description = models.CharField(max_length=30) isactive = models.BooleanField(default=True) class SUBCategories(models.Model): category_name = models.ForeignKey(Category, on_delete=models.CASCADE) sub_categories_name = models.CharField(max_length=30) sub_categories_description = models.CharField(max_length=30) isactive = models.BooleanField(default=True) below is the shoppingpage.html {% for result in category %} <div class="col-md-3"> <div class="lynessa-listitem style-01"> <div class="listitem-inner"> <a href="/9-6wear" target="_self"> <h4 class="title">{{result.category_name}}</h4> </a> {% for ans in subcategory %} <ul class="listitem-list"> <li> {% if ans.category_name == result.category_name %} <a href="/kurta" target="_self">{{ans.sub_categories_name}}</a> {% endif %} </li> </ul> {% endfor %} </div> </div> </div> {% endfor %} Help is greatly appreciated thanks!