Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Proper way of adding Custom Django Model Validation
As I was searching the ways of adding the model validation I found more than one way to achieve it. For eg if my model is as follows: from django.db import models from django.contrib.auth import get_user_model User = get_user_model() class ChatThread(models.Model): user1 = models.ForeignKey(User, on_delete=models.CASCADE) user2 = models.ForeignKey(User, on_delete=models.CASCADE) I want to validate such that user1 & user2 are different. Then I could have following options: override the save method implement clean or full_clean method use signals pre_save ... What would be the best approach for these kind of task ?? -
Selecting Many to Many fields based on selected foreign key drop down in django admin
I have the below models. In Django Admin, for course, how to show subcategories based on the selected category. I have tried django_smart_selects but the ChainedManyToManyField works for a many to many field but not a foreign key field. Any suggestions would be helpful. class category(models.Model): name= models.CharField(db_column='Name', max_length=2000, blank=True, null=True) class SubCategory= (modles.Model): name= models.CharField(db_column='Name', max_length=2000, blank=True, null=True) category= models.ForeignKey(category, on_delete= models.CASCADE) class Course(models.Model): name= models.CharField(db_column='Name', max_length=2000, blank=True, null=True) category= models.ForeignKey(category, on_delete= models.CASCADE) subcategory= models.ManytoManyField(SubCategory) -
Django-Crontab on action
How can I start a new cronjob for every new user that registers? This is what I have: CRONJOBS = [ ('*/1 * * * *', 'app.views.my_scheduled_job') ] def my_scheduled_job(): # do something user-related pass Thank you for any suggestions. -
How to enable Street View in GeoDjango
I am using the Django's PointField(...) in my model as # models.py from django.contrib.gis.db import models class Location(models.Model): name = models.CharField(max_length=100) point = models.PointField() Then, I configured the admin.py as normal, from django.contrib import admin class LocationModelAdmin(admin.ModelAdmin): list_display = ("id", "name",) list_display_links = ("id", "name",) admin.site.register(Location, LocationModelAdmin) But, when I am trying to add the entry via Django Admin, I am getting the areal view of the map Q: How can I change this areal view to a street-view? -
Select2 Issue with backend as '\t' save into database, how to fix it?
I am trying to save multiple select dropdown data into my database and i am using select2 class for the same, but in my backend the data save in format like ['\tdataname1\t', '\tdataname2\t']. i want to fix it and save data as 'dataname1', 'dataname2', ##for data in data:## ## print(data)## ## Model(fieldname=data)## i tried this way but first value of selected data will store into database, here is the image of single valu saved through forloop, and multiple value saved with back slash. image contains two columns and two types of data saved, one is without back slash but only single value of multiselect dropdown, and another one is of multiple data save with back slash -
How to restrict non staff users from accessing django-admin
My django-admin page is located at http://127.0.0.1:8000/admin/ Suppose there are 3 users in my website. Superuser Staff End user If anyone of these three users tries to access this link http://127.0.0.1:8000/admin/, 1st and 2nd can access it. And End User is not able to access it. Till this, it is fine. What I want is to do is to show Error 404 to End User. He/She should never know that this link is for admin page. Moreover, if anyone is not logged in, they should also see same 404 Page. I have referred this link but it takes me to another default page. PFA for the same PS: I am using Signin With Google, so it should not redirect me there. I am trying this since 3 continous days, so any help is highly appreciated. Thanks in advance. -
'QuerySet' object has no attribute 'related_uuid' - django object filter
you need to output the queryset in html html does not output data {% for related_item in related_uuid %} Related: {{ related_item.related_uuid }} {% endfor %} views class OrdersHomeView(ListView): model = Orders template_name = 'orders/orders_list.html' context_object_name = 'orders' def get_context_data(self, *, object_list=None, **kwargs): context = super().get_context_data(**kwargs) related_uuid = Clients.objects.filter(related_uuid='xxx')) context['related_uuid'] = related_uuid print('related_uuid', related_uuid.related_uuid) >> terminal AttributeError: 'QuerySet' object has no attribute 'related_uuid' return context models class Clients(models.Model): name = models.CharField(max_length=150, verbose_name='Имя') related_uuid = models.CharField(max_length=22, blank=True, verbose_name='uuid') -
How do I write to nested parent in Django Serializer
I'm using Django serializers to create an API which I both read from and write to. Models: class Biomarker(models.Model): low_value_description = models.TextField(blank=True, null=True) high_value_description = models.TextField(blank=True, null=True) class BiomarkerReading(models.Model): biomarker = models.ForeignKey(Biomarker, on_delete=models.CASCADE) test = models.ForeignKey(Test, on_delete=models.CASCADE) value = models.DecimalField(max_digits=30, decimal_places=8, default=0) Serializer: class BiomarkerReadingSerializer(serializers.ModelSerializer): class Meta: model = BiomarkerReading fields = ( 'id', 'test', 'biomarker', 'value' ) JSON format: { "id": 617188, "test" 71829, "biomarker": 32, "value": 0.001 } The above all works, and I can read and write to it with that JSON format. However I now need to add some fields from the parent model so the response looks like this: { "id": 617188, "test" 71829, "biomarker": { "id": 32, "low_value_description": "All good", "high_value_description": "You will die", }, "value": 0.001 } I have got the read part working using these Serializers: class BiomarkerDescriptionSerializer(serializers.ModelSerializer): class Meta: model = Biomarker fields = ('id', 'low_value_description', 'high_value_description') class BiomarkerReadingSerializer(serializers.ModelSerializer): biomarker = BiomarkerDescriptionSerializer() class Meta: model = BiomarkerReading fields = ( 'id', 'test', 'biomarker', 'value' ) However I can't find a way to write to it using the old json format (with "biomarker": 32 in the JSON). I thought I would need to do something in validate or create, but I get … -
MongoDB Document_count data per month
One of my functions im using to pull count values of MongoDB data is, for me at least, slowing the applicaion down. Here is the code im using def build_year_graphs(year): Jan = collection.count_documents({'DateTime':{'$gt':year+"-01-01",'$lt':year+"-02-01"}, 'IsAsset':'True'}) Feb = collection.count_documents({'DateTime':{'$gt':year+"-02-01",'$lt':year+"-03-01"}, 'IsAsset':'True'}) Mar = collection.count_documents({'DateTime':{'$gt':year+"-03-01",'$lt':year+"-04-01"}, 'IsAsset':'True'}) Apr = collection.count_documents({'DateTime':{'$gt':year+"-04-01",'$lt':year+"-05-01"}, 'IsAsset':'True'}) May = collection.count_documents({'DateTime':{'$gt':year+"-05-01",'$lt':year+"-06-01"}, 'IsAsset':'True'}) Jun = collection.count_documents({'DateTime':{'$gt':year+"-06-01",'$lt':year+"-07-01"}, 'IsAsset':'True'}) Jul = collection.count_documents({'DateTime':{'$gt':year+"-07-01",'$lt':year+"-08-01"}, 'IsAsset':'True'}) Aug = collection.count_documents({'DateTime':{'$gt':year+"-08-01",'$lt':year+"-09-01"}, 'IsAsset':'True'}) Sep = collection.count_documents({'DateTime':{'$gt':year+"-09-01",'$lt':year+"-10-01"}, 'IsAsset':'True'}) Oct = collection.count_documents({'DateTime':{'$gt':year+"-10-01",'$lt':year+"-11-01"}, 'IsAsset':'True'}) Nov = collection.count_documents({'DateTime':{'$gt':year+"-11-01",'$lt':year+"-12-01"}, 'IsAsset':'True'}) Dec = collection.count_documents({'DateTime':{'$gt':year+"-12-01",'$lt':year+"-12-31"}, 'IsAsset':'True'}) YearData ={'Jan':Jan, 'Feb':Feb, 'Mar':Mar, 'Apr':Apr, 'May':May, 'Jun':Jun, 'Jul':Jul, 'Aug':Aug, 'Sep':Sep, 'Oct':Oct, 'Nov':Nov, 'Dec':Dec} return YearData This returns each month and a value. It works. But its slow. I feel there is a better way to achieve this.. however i dont seem to be able to acomplish this. Ive been looking at using mongo .aggregate to do this but in all honesty, its not working for me Thanks in advance! -
Default template names for password reset in django custom user registration model
I am working on overriding the default user registration model using the AbstractUser model as suggested in the documentation, i.e. by creating a new user model named: class CustomUser (AbstractUser): pass Everything is perfect and the user login, signup, and logout works well. Now, my challenge is that I want to change the default templates for password reset. I have managed to do so for the first two steps by creating new templates under the /templates/account folder. These are named: password_reset.html and password_reset_done.html. My problem is the naming for the other remaining templates in the subsequent steps. Most of the tutorials call it: password_reset_confirm.html and password_reset_complete.html. However, I tried these but none seems to override. I have checked around but there is no mention of the template names. Could anyone be knowing the names that I should be using for the last two templates so as to override the default templates provided by Django? -
How to provide SerializerMethodField input from view.py in django Rest Framework
I am using Django DRF, and having difficulty in applying SerializerMethodField (https://www.django-rest-framework.org/api-guide/fields/#serializermethodfield) Following is a simple case of typical model, serializer code, which works perfectly. serializer.py (before) from django.contrib.auth.models import User from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' view.py (before) @api_view(['GET']) def GetAllUsers(request): Users = User.objects.all() serializer = UserSerializer(Users, many=True) return Response(serializer.data) In order to deliver additional information which is not included in the model, I changed serializer serializer.py (after) from django.contrib.auth.models import User from django.utils.timezone import now from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): days_since_joined = serializers.SerializerMethodField() class Meta: model = User def get_days_since_joined(self, obj): return (now() - obj.date_joined).days Now I have to find a way to give obj(which has date_joined inside) to serializer, and I think I have to do it in view.py But I don't know how to do it. Thanks -
Django-filters create filter with custom lookup expression
I'm using django-filters and want to create possibility for users to choose lookup expressions, something like code below, but I don't know how I could provide expression to filter. What I'm trying to get as result is something like Product.objects.filter(description__expression=value). Does anyone knows the way how to do it? class ChooseLookupExprCharFilter(filters.CharFilter): def filter(self, qs, value, expression='icontains'): if value in EMPTY_VALUES: return qs if self.distinct: qs = qs.distinct() lookup = '%s__%s' % (self.field_name, expression) qs = self.get_method(qs)(**{lookup: value}) return qs class ProductFilterSet(filters.FilterSet): description = ChooseLookupExprCharFilter(label='description') class Meta: model = Product fields = ('name', 'description', 'prize') -
Advanced/Complex Django ORM Operation - Help Needed Please! :)
I'm having a little difficulty conceptualising a particular query I would like to make, based off both my own (solid intermediate) knowledge of the Django ORM and every blog post, guide and documentation I have at my disposal. But still, I'm unsure. I have been able to most of the heavy lifting in the database, with a few inefficient loops here and there to organise the data as I need it. However, I would like to optimise it further by doing more heavy lifting in the DB and making use of Django's lazy evaluation. To conceptualise the system: We have the notion of a "Job" with "skills" (a ManyToManyField to the Skill object). We have the notion of a User. We have the notion of a Proficiency, an object which links a User, a Skill and provides a rating out of 10. We have the notion of a Candidate, an object matches links a User to a Job, based off of their scoring "proficiensies" for each skill in job.skills.iterator(). So, out setup to "match" Jobs and Users is currently as follows: # Base users queryset: users = User.objects.filter( is_staff=False, is_superuser=False, is_active=True ).prefetch_related( 'proficiencies' ) for user in users.iterator(): proficiencies = … -
Django- How to get last uploaded file into template?
I am making a site where users can upload sound files. They can see the list of user-uploaded sound files and play them. This much works. I have made a for loop of the object list with audio elements. However, additionally, I also want to be able to place only the most recently added sound file on its own at the bottom of the template so that it can be dealt with separately (i.e. I want to put it in an audio element separate from those in the list and also be able to access it on its own in the template to process it using WebAudio API). I know I need to use a filter and I keep reading that Model.objects.latest(‘field’) should do the job (I assume in views.py) but I am doing something very wrong as whatever I put in my view and my template creates errors. I am using class-based views and Django version 3.1.7 If anyone can show me with what I need to put into my model, my view, and my template so that I can get just the last added sound file into my template from the object list. I would be very grateful. … -
Django how to do validate method for the same user to not exist again?
this is my code models.py class UserAttributes(models.Model): airport = models.ForeignKey('airport.Airport', related_name='user_attributes_airport', on_delete=models.SET_NULL, null=True, blank=True) location = PointField(blank=True, null=True) user = models.ForeignKey( 'users.AerosimpleUser', related_name='user_attributes', on_delete=models.CASCADE, null=True, blank=True) views.py class LocationViewSet(viewsets.ModelViewSet): serializer_class=LocationRetrieveSerializer http_method_names = ['get', 'post', 'patch', 'put'] def get_permissions(self): switcher = { 'create': [IsAuthenticated], 'list': [IsAuthenticated], 'retrieve': [IsAuthenticated], 'update': [IsAuthenticated], 'partial_update': [IsAuthenticated], } self.permission_classes = switcher.get(self.action, [IsAdminUser]) return super(self.__class__, self).get_permissions() def get_queryset(self): return UserAttributes.objects.filter( airport__id=self.request.user.aerosimple_user.airport_id).order_by('pk') serializers.py class LocationRetrieveSerializer(serializers.ModelSerializer): class Meta: model = UserAttributes fields = '__all__' def create(self, validated_data): if UserAttributes.objects.filter(user=self.context["request"].user).exists(): raise serializers.ValidationError("User Already exists.") if UserAttributes.objects.filter(airport=self.context['request'].user.aerosimple_user.airport).exists(): raise serializers.ValidationError("Airport Already exists.") user_attributes = UserAttributes.objects.create(**validated_data) return user_attributes while trying this i am getting the following error Cannot query "8f21af88-c78e-493e-b40c-a874573a2207": Must be "AerosimpleUser" instance. -
How to develop cascading/nested filters in api django which are dynamically updated
I am working on an API driven Django application whose frontend is developed in React. Now I have one analytics page in UI where user can filter data based on 8-9 filters (Multi select dropdowns). The requirement is such that all the filters should only have the applicable values in the list. Currently, I am updating those filter values on each select. Due to which, I am hitting the database 10 times (one for filtering the actual data and one time each for 9 filters) which I think is not efficient. I am using Django Rest Framework for API creation. What is the ideal way of doing this? Any help would be appreciated. Thanks in advance! -
How to run the "manage.py runserver" command in PyCharm by pressing the up arrow on every time?
When I open the Pycharm the first time or killed the terminal after executing some commands, I need to type the "manage.py runserver" command (or other commands) every time. Is it possible to run the last used command by pressing the up arrow? -
Bootstrap Carousal doesn't change next/previous picture
So I've been trying to make a portfolio website in Django, I've been following some tutorial for this. The Carousal on my page doesn't seem to change images when clicking next/previous button. The images displays properly (need to resize it for appropriate looks) but no matter what I do it won't show next/previous image. I am providing the carousal code and the whole html code: Carousal code: <div id="carouselExampleControls" class="carousel slide" data-ride="carousel"> <div class="carousel-inner"> <div class="carousel-item active"> <img class="d-block w-100" src="https://source.unsplash.com/1600x800/?food,food" alt="First slide" style="width:100%;"> </div> <div class="carousel-item active"> <img class="d-block w-100" src="https://source.unsplash.com/1600x800/?cat,cat" alt="Second slide" style="width:100%;"> </div> <div class="carousel-item active"> <img class="d-block w-100" src="https://source.unsplash.com/1600x800/?car,car" alt="Third slide" style="width:100%;"> </div> </div> <a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> Whole HTML code: <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous"> <script src="js/bootstrap.js"></script> <title>Home</title> </head> <body> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <div class="container-fluid"> <a class="navbar-brand" href="#">OMEGA</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria- expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> <li class="nav-item"> <a class="nav-link … -
Django extremely slow page loads when using remote database
I have a working Django application running fine locally using an sqlite3 database. However, when I change the Django database settings to use my external AWS RDS database all my pages start loading extremely slow. Sometimes up to 40 seconds latency for each page. I have checked my AWS metrics and my instance is not even close to being fully utilized. How can I diagnose what is causing this latency? My app was finished and getting ready to be deployed so I am desperate for answers at this point.. AWS monitoring -
Performing actions on a related model while saving
Guys and girls, I need help. For several days now I have been unable to figure out how to get around one problem. I would appreciate any idea or advice. For simplicity, there is a set of models: class A(models.Model): name = models.CharField(max_length=255) class B(models.Model): name = models.CharField(max_length=255) owner = models.ForeignKey(A, on_delete=models.CASCADE, null=False) def foo(): do something The number of instances of B belonging to A is not known in advance. The number of instances of B is determined by the user at the time of creating a new instance of A. Moreover, he can create an instance of A without creating a single instance of B (empty set). Challenge: I need to run foo after saving a new instance of A. This function should handle both the fields of the new instance of A and fields of B (back relation). Yes, I set the receiver to post_save signal model A. But here's the problem, at the moment when A is already saved (post_save), instances of B have not yet been saved (pre_save), and the values of the corresponding fields have not been determined. In other words, I cannot get raw B values in receiver A. Any ideas? Am I … -
celery worker ,is not working ,if i can write project name then working and results is not disabled
-------------- celery@krishna-H310M-S2 v5.0.5 (singularity) --- ***** ----- -- ******* ---- Linux-5.8.0-45-generic-x86_64-with-glibc2.29 2021-03-17 17:04:03 *** --- * --- ** ---------- [config] ** ---------- .> app: default:0x7ff4a3f2cf70 (.default.Loader) ** ---------- .> transport: amqp://guest:**@localhost:5672// ** ---------- .> results: disabled:// *** --- * --- .> concurrency: 4 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery -
I am trying to deploy(ubuntu18.04) my DAJNGO application using django-channels, redis, nginx and daphne for websocket connection
NGINX CONFIG FILE Browser Error Nginx error Daphne Config File -
Redirect/Render many pages in DJANGO at once
I write a project in django. I've got data from MS SQL called orders - there are few rows from the table. I would like to loop it, and each of them should render new tab '/print' with some context. Like: for o in orders: HttpResponseRedirect('/print') Is this possible? -
V model on input texbox on key up updates text on other v model input text in django for loop
I have this Django for loop where i have this form with input textbox that has v model. When i type a text on it , on key up it updates text on ther input texbox inside this django for loop : {% for drama in theatre %} <div class="comment-input" id="postcomment-{{tweet.id}}"> <form v-on:submit.prevent="submit0comment({{tweet.id}})" id="comment-{{tweet.id}}" > <input id=".input_1" type="text" v-model="comment_body" class="form-control"> <div class="fonts"> <button class="btn-share">Post</button> </div> </form> </div> <br> <div class="d-flex flex-row mb-2" v-for="comment in comments"> <img :src="comment.avatar" width="40" class="rounded-image"> <div class="d-flex flex-column ml-2"> <span class="name">[[comment.commenter]]</span> <small class="comment-text">[[ comment.comment_body]]</small> <div class="d-flex flex-row align-items-center status"> <small>Like</small> <small>Reply</small> <small>[[ comment.created_at ]]</small> </div> </div> </div> {% endfor %} -
not able to hide result count in django admin list view
I have added the following in my admin file and the related pagination functions are below. But there is no change. Count is not disabled in any of the places and the list view is very slow as there are many items. My Backend is SQL server. paginator = NoCountPaginator show_full_result_count = False from cached_property import cached_property from django.core.paginator import Paginator from django.db import connection, transaction, OperationalError class NoCountPaginator(Paginator): @cached_property def count(self): return 20 class TimeLimitedPaginator(Paginator): @cached_property def count(self): # We set the timeout in a db transaction to prevent it from # affecting other transactions. with transaction.atomic(), connection.cursor() as cursor: cursor.execute('SET LOCK_TIMEOUT 200;') try: return super().count except OperationalError: return 9999999999