Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
searching multiple tags django taggit
I wanna add a tag system that i could search for multiple tags i know i could use taggit but it doesnt allow for a multiple tag searching and i want to select tags from a list and add multiple tags like this one from groups here is my tags genres =( ("FPS", "FPS"), ("RPG", "RPG"), ("Action-Adventure", "Action-Adventure"), ("Anime", "Anime"), ("Series/Movie Games", "Series/Movie Games"), ("Indie", "Indie"), ("Online", "Online"), ("Coop", "Coop"), ("Great Story", "Great Story"), ("Great Environment", "Great Environment"), ("Horror", "Horror"), ("Underrated", "Underrated"), ("Third Person", "Third Person"), and here's models class Post(models.Model): picture = models.CharField(max_length=100,default='') names = models.CharField(max_length=100,default='') critique = models.TextField(default='') score = models.IntegerField(default=50) genre = models.CharField(max_length=100,choices=genres,default='____') -
create an appointment app with registered user and non registered user in Django
I want to create an appointment app with Django with the following condition: doctors and reception can add appointments for registered patients patient who already register can add appointment only for them self doctors and reception can add appointments for non register patient(Temporary patient, for example) in the first and the 2nd condition, no need for adding information about the patient (because he adds them) in the 3rd doctor and reception have the ability to add information i'm trying with this but for now i'm stuck here is my models.py class User(AbstractUser): STATUS_CHOICES = (('paitent', 'paitent'), ('Doctor', 'Doctor'), ('reception', 'reception'), ('temporary', 'temporary')) STATUS_CHOICES_2 = (('yes', 'yes'), ('no', 'no')) type_of_user = models.CharField(max_length=200, choices=STATUS_CHOICES, default='paitent') allowd_to_take_appointement = models.CharField(max_length=20, choices=STATUS_CHOICES_2, default='yes') def is_doctor(self): if self.type_of_user == 'Doctor': return True else: return False def is_paitent(self): if self.type_of_user == 'paitent': return True else: return False def is_reception(self): if self.type_of_user == 'reception': return True else: return False def is_temporary(self): if self.type_of_user == 'temporary': return True else: return False def can_add_appointement(self): if self.allowd_to_take_appointement == 'yes': return True else: return False class Profile(models.Model): BLOOD_GROUPS = [ ('O-', 'O-'), ('O+', 'O+'), ('A-', 'A-'), ('A+', 'A+'), ('B-', 'B-'), ('B+', 'B+'), ('AB-', 'AB-'), ('AB+', 'AB+'), ] GENDER_CHOICES = (('M', 'Male'), ('F', … -
Case Insensitive search with POstgres Similar To
I have such query in my Django code cond = self.text_query(field.id, f''' EXISTS( SELECT * FROM {self.fieldvalue_db_view} WHERE entry_id = {self.db_table}.id AND {self.fieldvalue_db_view}.field_id = {field.id} AND {self.fieldvalue_db_view}.{text_search_column} SIMILAR TO %(pattern)s ) ''', dict(pattern='%' + val + '%')) When val = '%%john smith%%' or val = '%%john%smith%%' it did not return a result like 'John smith', but if val = '%%john%smith%|%smith%john%%' it returns results with 'John smith'. How this case sensitiveness can be solved? Thanks, -
How to execute PostgreSQL query in Django
I am trying to fetch the PostgreSQL table onto HTML using Django, When I execute the spatial query in the query Tool of PostgreSQL I got the perfect results, but When I'm trying to execute the same script from Django getting all rows of data. Thank you for helping in advance. SQL query which is working perfectly SELECT * FROM jhk_schls as point,jhk_urban as polygon WHERE ST_Within(point.geom, polygon.geom) Django Script def search(request): if request.method == "POST": first_layer = request.POST.get('first_layer') spati_func = request.POST.get('spa_func') second_layer = request.POST.get('secon_layer') within_fun = 'select * from' + " " + str(first_layer) + " " + 'as point,' + str(second_layer) + " " + 'as polygon' + " " + 'WHERE' + " " + str(spati_func)+'(point.geom, polygon.geom)' cursor = connection.cursor() cursor.execute(within_fun) data = cursor.fetchall() return render(request, 'geoit/search.html',{ 'data':data}) return render(request,'geoit/search.html') HTML <span>Select Layer</span> <select name="first_layer"> <option value="-1" disabled selected >Please select</option> Layer<li><option value="jhk_schls">jhk_schls</option></li> </select> </br> <span>Spatial Functions</span> <select name="spa_func"> <option value="-1" disabled selected >Please select</option> Layer<li><option value="ST_Within">ST_Within</option></li> </select> </br> <span>Select Layer</span> <select name="secon_layer"> <option value="-1" disabled selected >Please select</option> Layer<li><option value="jhk_urban">jhk_urban</option></li> </select> <input type="submit" value="submit"> </p> </div> </form> <button type="submit" value="submit"><i class="fa fa-search"></i> </button> </form> <p></p> <center> <table> {% for item in data %} <tr> <td>{{ item.0 … -
StreamingHttpResponse doesn't block other requests in wsgi but does on channels asgi
Recently I wrote a django wsgi server. it has a webcam stream and at the same time handles requests like get users or save image and other stuff. in the wsgi vesion the server worked flawlessly. at the sametime that the stream was showing footage the other requests could be handled and the server wasn't blocked. but when i switched to channels asgi because i wanted the websocket feature all fell apart. when the stream started the entire server froze and not even the websocket connected. even if the websocket was connected before the stream when the stream starts nothing works. WSGI Version def get_stream(): cap = cv.VideoCapture(0) while True: frame, _ = cap.read() valid, img = cv2.imencode('.jpg', frame) yield(b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + img.tobytes() + b'\r\n\r\n') @api_view(['GET']) def stream(): return StreamingHttpResponse(get_stream(), content_type='multipart/x-mixed-replace;boundary=frame') @api_view(['GET']) def get_users(): .... ASGI Version def get_stream(): cap = cv.VideoCapture(0) while True: frame, _ = cap.read() valid, img = cv2.imencode('.jpg', frame) yield(b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + img.tobytes() + b'\r\n\r\n') @api_view(['GET']) def stream(): return StreamingHttpResponse(get_stream(), content_type='multipart/x-mixed-replace;boundary=frame') @api_view(['GET']) def get_users(): .... class consumer(WebsocketConsumer): def connect(self): self.accept() def disconnect(self, code): self.close() def receive(self, text_data=None, bytes_data=None): pass -
JsonRespone() not working in django when using formvalidation.io
I am using formvaladation.io for HTML form validation and I save data using ajax when I press the submit button data inserted successfully into the database, but JsonResponse() print dictionary like {'saved':1} to the webpage instead of giving javascript alert, then I figure out this thing happens because of I using formvalidation.io, when I don't use form validation it's working properly and JsonResponse return data to ajax success function and give javascript alert in the page. so I think there is some mistake in the form validation javascript file, I request you to help further in my code. HTML FILE <form method="post" id="patient"> {% csrf_token %} *** // All input tags are here i am not able to show it because there are many input box *** <div class="card-footer"> <div class="d-flex justify-content-end"> <input type="submit" class="btn btn-light-success btn-lg mr-2 font-weight-bold"> <input type="reset" class="btn btn-light-danger btn-lg font-weight-bold"> </div> </div> </form> Ajax call from HTML FILE <script> $(document).on('submit', '#patient', function (e) { e.preventDefault(); $.ajax({ type: 'POST', url: '{% url ' Patient: add ' %}', data: $("#patient").serialize(), dataType: 'json', success: function (data) { if (data.saved === 1) { alert("Data Saved"); } } }); }); </script> patient_valadation.js FILE var form = document.getElementById('patient'); document.addEventListener('DOMContentLoaded', function(e) { … -
Django filters form doesn't change the list of hotels
i have a search view that takes input from a search bar and returns a list of hotels in search_results.html class SearchResultsView(ListView): model = Hotel template_name = 'search_results.html' context_object_name = 'hotels_list' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['filter'] = HotelFilter(self.request.GET, queryset=self.get_queryset()) return context def get_queryset(self): if not self.request.session['myCountry']: self.request.session['myCountry'] = self.request.GET.get('myCountry') self.request.session['myCity'] = self.request.GET.get('myCity') or '' self.request.session['myDeparture'] = self.request.GET.get('myDeparture') self.request.session['myArrival'] = self.request.GET.get('myArrival') self.request.session['myPeople'] = self.request.GET.get('myPeople') country = self.request.GET.get('myCountry') or self.request.session['myCountry'] city = self.request.GET.get('myCity') or self.request.session['myCity'] start_date = self.request.GET.get('myDeparture') or self.request.session['myDeparture'] end_date = self.request.GET.get('myArrival') or self.request.session['myArrival'] people = self.request.GET.get('myPeople') or self.request.session['myPeople'] results = Hotel.objects.raw('select h.id, h.single_rooms_number - coalesce(sum(r.single_rooms_number), 0) as SR, ' 'h.double_rooms_number -coalesce(sum(r.double_rooms_number), 0) as DR, ' 'h.twin_rooms_number - coalesce(sum(r.twin_rooms_number), 0) as TR, ' 'h.triple_rooms_number -coalesce(sum(r.triple_rooms_number), 0) as TRR, ' 'h.apartments_number - coalesce(sum(r.apartments_number), 0) as AR ' 'FROM globe_hotel h ' 'LEFT JOIN (SELECT * FROM globe_reservations WHERE start_date >= %s or end_date <= %s) r on h.id=r.hotel_id_id ' 'LEFT JOIN globe_city ci on h.city_id_id=ci.id ' 'LEFT JOIN globe_country ct on ct.id=ci.country_id_id ' 'WHERE LOWER(ct.name::text) = LOWER(%s) ' 'GROUP BY h.id ' 'HAVING coalesce(h.single_rooms_number, 0) - coalesce(sum(r.single_rooms_number), 0) + ' '(coalesce(h.double_rooms_number, 0) - coalesce(sum(r.double_rooms_number), 0))*2 + ' '(coalesce(h.twin_rooms_number, 0) - coalesce(sum(r.twin_rooms_number), 0))*2 + ' '(coalesce(h.triple_rooms_number, 0) -coalesce(sum(r.triple_rooms_number), 0))*3 + ' … -
Unable to display custom error message in django template
I am new in python django framework. I am trying to display custom validation error message in registration form template but i am not able to display custom validation error message in registration template. Please review my code below and let me know what i am doing wrong in my project. Thanks views.py from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm from .forms import CreateUserForm from django.contrib import messages from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required def index(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): form.save() user = form.cleaned_data.get('username') messages.success(request, 'Your account was created.') return redirect('login') context = {'form': form} return render(request,'register.html',context) form.py from django.db import models from django.forms import ModelForm, fields from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms class CreateUserForm(UserCreationForm): first_name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}), error_messages = {"required":"The first name field is required"}) last_name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}),required=False) username = forms.CharField(widget = forms.TextInput(attrs={'class': 'form-control'}), error_messages = {"required":"The username field is required"}) email = forms.EmailField(widget=forms.TextInput(attrs={'class':'form-control'}), error_messages = {"required":"The email field is required"}) password1 = forms.CharField(label = 'Password',widget=forms.PasswordInput(attrs={'class':'form-control'}), error_messages = {"required":"The password field is required"}) password2 = forms.CharField(label = 'Password Confirm',widget=forms.PasswordInput(attrs={'class':'form-control'}), error_messages ={ "required":"The password confirm field is required"}) class Meta(UserCreationForm.Meta): … -
Why my form.py can't read field HEIGHT from models?
I am trying to run my app, however I get this error: NameError: name 'HEIGHT' is not defined This is my models.py: from django.db import models from django.forms import ModelForm HEIGHT = [ ('XS', 'Extra Small'), ('S', 'Small'), ('M', 'Medium'), ('L', 'Large'), ('XL', 'Extra Large')]class Dog(models.Model): class Dog(models.Model): name = models.CharField(max_length=20) age = models.IntegerField(null=False) weight = models.IntegerField(null=False) height = models.CharField(max_length=2, choices=HEIGHT, null=False) class DogForm(ModelForm): class Meta: model = Dog fields = ['name', 'age', 'weight', 'height'] This is my forms.py: from django import forms class DogForm(forms.Form): name = forms.CharField(max_length=20) age = forms.IntegerField() weight= forms.IntegerField() height = forms.CharField(max_length=2, widget=forms.Select(choices=HEIGHT)) What am I doing wrong? -
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!