Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
CSS Grid not working in dynamically generated items with Django jinja templating?
I am new to Django and ran into this issue. so basically I am making an app where I have to display rooms on the main home page. The rooms are generated dynamically and are stored in the database that are fetched for the home page like this (in the views.py) def home(request): return render(request, 'base/index.html', {'rooms':rooms}) then the index.html will display the data in the form of cards using jinja for loop, something like this, just ignore the classes and all that, they are just dummy images, here I am using tailwind-css for styling {% for room in rooms %} <div class="grid grid-cols-1 md:grid-cols-3 border-4 border-red-400 lg:grid-cols-4 sm:grid-cols-2 gap-10"> <div class="rounded overflow-hidden border-4 border-red-400 shadow-lg"> <a href="/room/{{room.id}}"> <div class="relative"> <img class="w-full" src="https://images.pexels.com/photos/196667/pexels-photo-196667.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" alt="Sunset in the mountains"> <div class="hover:bg-transparent transition duration-300 absolute bottom-0 top-0 right-0 left-0 bg-gray-900 opacity-25"> </div> <a href="#!"> <div class="absolute bottom-0 left-0 bg-indigo-600 px-4 py-2 text-white text-sm hover:bg-white hover:text-indigo-600 transition duration-500 ease-in-out"> {{room.id}} </div> </a> <a href="!#"> <div class="text-sm absolute top-0 right-0 bg-indigo-600 px-4 text-white rounded-full h-16 w-16 flex flex-col items-center justify-center mt-3 mr-3 hover:bg-white hover:text-indigo-600 transition duration-500 ease-in-out"> <span class="font-bold">27</span> <small>March</small> </div> </a> </div> </a> <div class="px-6 py-4"> <a href="#" class="font-semibold text-lg inline-block hover:text-indigo-600 transition duration-500 … -
Django Rest Framework - DataError: integer out of range
I'm creating an Urban Dictionary style website where I have one django model: class Term(models.Model): term_name=models.CharField(max_length=100) definition=models.TextField() example=models.ImageField(blank=True) uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) tags = TaggableManager(blank=True) def __str__(self): return self.term_name I'm using taggit to add tags, but when I test out adding tags through the Django Rest Framework, I get an error reading: Internal Server Error: /api/glossary/a9cc167c-f5c2-11ec-a11a-1e4794e8627e Traceback (most recent call last): File "/Users/almoni/.local/share/virtualenvs/screenplayrules_django-lZL7DxO_/lib/python3.9/site-packages/django/db/models/query.py", line 657, in get_or_create return self.get(**kwargs), False File "/Users/almoni/.local/share/virtualenvs/screenplayrules_django-lZL7DxO_/lib/python3.9/site-packages/django/db/models/query.py", line 496, in get raise self.model.DoesNotExist( taggit.models.TaggedItem.DoesNotExist: TaggedItem matching query does not exist. followed by a ton of File errors then: django.db.utils.DataError: integer out of range My process before getting this error was to just test out tags = TaggableManager(blank=True) I had in my Term model. So I went over to localhost:8000 and tried to PUT a tag: Once I clicked put I get the error I previously showed in my terminal and this page error: I'm still pretty new to django and have never used taggit before, so I'm a bit confused here. -
Database query failing in django views when using filter
Just going through the Django tutorial and am playing around and testing stuff. My question is, how come the following line works and lets me go to page no problem: test = Choice.choices.all() While the following filter line gives me the error message ValueError: too many values to unpack (expected 2) test = Choice.choices.get("question_id=6") Even when I try the following two lines it doesn't work. No idea what's happening or why test = Choice.choices.get("question_id=6")[0] test = Choice.choices.get("question_id=6")[0].question_text I feel like i need to really understand what's going on and why so I can actually do proper queries in the future -
how to use django python framework with MERN Stack technology to create a web application?
I am working on a MERN Stack project. My frontend is designed in javascript with Reactjs and is connnected to a backend designed in javascript with Expressjs, MongoDB, Nodejs. However, I would like to connect my frontend to Django so that he can send him data and he will send him the data obtained on the web. However, when I search the internet I see full stack tutorials with Reactjs and Django or Reactjs in MERN Stack. However, my frontend needs Django to do a specific task and others MERN technologies namely MongoDB, Nodejs, Expressjs to do other tasks. I don't know if and how I can use Django with MERN. I searched the internet if my frontend could have two backends, but I didn't get any relevant results. Because my problem is that I can easily pass data from the frontend to Django and Django can easily send this data back to the frontend despite using MERN technology. -
How to pass and update data into different tables in a single post function in Django Rest Framework
I have two models named TokenDetails and TimeInterval.I have to post a time into TokenDetails models as bookingtime and in TimeInterval I have a field status which by default is True and if the bookingtime field in TokenDetails is todays date i have to change the status of TimeInterval into False TokenDetails.models.py class TokenDetail(models.Model): customername=models.ForeignKey('accounts.User', on_delete=models.CASCADE,null=True) bookingdate=models.DateField(default=datetime.date.today) bookingtime=models.ForeignKey('vendor.TimeInterval',on_delete=models.CASCADE,null=True) servicename=models.ForeignKey('vendor.ServiceDetail',on_delete=models.CASCADE,null=True) vendorname=models.ForeignKey('vendor.VendorDetail',on_delete=models.CASCADE,null=True) TimeInterval.models.py class TimeInterval(models.Model): timeinterval=models.TimeField(default=None) serviceid=models.ForeignKey('ServiceDetail',on_delete=models.CASCADE,null=True) userid=models.ForeignKey('accounts.User',on_delete=models.CASCADE,null=True) status=models.BooleanField(default=True) def __str__(self): return str(self.timeinterval) views.py @api_view(['POST']) def tokendetailsAdd(request): if request.method=='POST': customername=request.data.get('customerid') custname=User.objects.get(id=customername) bkngdate=request.data.get('bookingdate') bookingtime=request.data.get('bookingtime') bkngtime=TimeInterval.objects.get(id=bookingtime) servicename=request.data.get('servicename') srvcname=ServiceDetail.objects.get(id=servicename) vendorname=request.data.get('vendorname') vndrname=VendorDetail.objects.get(id=vendorname) sts=request.data.get('status') status=TimeInterval.objects.get(status=sts) TokenDetail.objects.create( customername=custname, bookingdate=bkngdate, bookingtime=bkngtime, servicename=srvcname, vendorname=vndrname, ) return Response('token registered') -
How do I prevent an admin (superuser) from changing/updating other user’s password?
I have a custom method for all users to reset password. It sends the password reset email to the user, user then click on password rest link and then resets his/her password. So, I want users to reset password only this way and don’t want any admin to reset any user password from Django Administration page. How do I prevent admin from changing/updating any other user’s password? I don’t have any custom Admin Model yet. If this requires me to create a custom Admin model, please explain a bit, what things I will have to keep in the model to keep all the other functionality same as default Admin Model? Just a slight change required and that is not to let admin change any other user’s password. -
Microsoft django logout
[I want to perform Microsoft logout from my Django application, I have logged IN my user and now I am sending few parameters 'tenant':'ec0a1000-3407-4d2f-81f9-dfd1179718dc', 'client_id' : 'f03b5c74-f63f-4bbd-a920-70c91b201c97', 'code' : code, 'client_secret' : '2hv8Q~oHdAeVS-DdmaJA6vZAaH8PzM.Inoeddb_P', 'redirect_uri' : 'http://localhost:8000/callback', 'scope' : 'user.read', 'grant_type' : 'authorization_code', but I got this error so can you please tell me the solution of this error. ]1 -
In Django admin list, link the model which doesn't have relationship with object
I have two models which doesn't have foreign key as relation but has the username column common. class User(models.Model): password = models.CharField(max_length=255) email = models.EmailField(unique=True, blank=True) username = models.CharField(max_length=255) class SessionUser(models.Model): username = models.CharField(max_length=255) last_login = models.DateTimeField(auto_now=True) I wanted to list all users in Django admin and once clicked on individual object it should list all the session of user. How can we link the object which doesn't have foregien key relationship? -
Getting error by setting a Dynamic Task Scheduling With Django-celery-beat
I'm setting up Dynamic cron based on the model creation to create another model object error im getting is Cannot assign "(<CrontabSchedule: 0 0 27 1 * (m/h/dM/MY/d) UTC>, True)": "PeriodicTask.crontab" must be a "CrontabSchedule" instance. this is my code where a periodic task will be created by creating this model import json from django.utils import timezone import uuid from django.db import models from django_celery_beat.models import CrontabSchedule, PeriodicTask # Create your models here. class Rule(models.Model): rule_id = models.UUIDField( primary_key = False, default = uuid.uuid4, editable = True) name = models.CharField('r=Rule Name',max_length=255,blank=True,null=True) compliance_frequency = models.CharField(max_length=40,choices=(('QUARTERLY','QUARTERLY'), ('MONTHLY','MONTHLY'),('YEARLY','YEARLY')),default='YEARLY') applicable_from = models.DateField(default=timezone.now) applicable_to = models.DateField(null=True,blank=True) task = models.OneToOneField( PeriodicTask, on_delete=models.CASCADE, null=True, blank=True ) def setup_task(self): self.task = PeriodicTask.objects.create( name=self.name, task='create_compliance', crontab=self.crontab_schedule, args=json.dumps([self.id,self.name,self.compliance_frequency]), start_time= timezone.now(), ) self.save() @property def crontab_schedule(self): if self.compliance_frequency == "QUARTERLY": return CrontabSchedule.objects.get_or_create(minute='0',hour='0',day_of_week='*', day_of_month='27',month_of_year='3,6,9,12') if self.compliance_frequency == "MONTHLY": return CrontabSchedule.objects.get_or_create(minute='0',hour='0',day_of_week='*', day_of_month='27',month_of_year='*') if self.compliance_frequency == 'YEARLY': return CrontabSchedule.objects.get_or_create(minute='0',hour='0',day_of_week='*', day_of_month='27',month_of_year='1') raise NotImplementedError( '''Interval Schedule for {interval} is not added.'''.format( interval=self.compliance_frequency. value)) now using signal.py i'm triggering the setup_task to setup the task from django.db.models.signals import post_save from django.dispatch import receiver from .models import Rule @receiver(post_save,sender=Rule) def create_periodic_task(sender, instance, created, **kwargs): if created: instance.setup_task() instance.task.enabled = True instance.task.save() print('signal working') then using trigger a task … -
Encoding a hyperlink in CSV formatted file doesn't work
The problem is here; f'=HYPERLINK("http://{os.getenv("OPTION_HOST_IP)}:8000/test/opt?sec={final_list[1]}&st={summary_row[4]}&exp={summary_row[1]}&cp={final_list[6]}", "Daily")'] This just returns text in LibreOffice What should I do? The other article told me to use double quotes ,but that doesn't work for me either. -
Axios/Django rest, cant filter with question mark
I'm having very stupid problem: I can't get to filter data I'm getting from django rest by any means. Using "/?something=value" does not thin out the results obtained, I'm still getting all the results. I tried using "param", but it basically does same thing and is still not working. I don't know if I'm missing something, but even when I go to views of my database it is not working. async created() { try { const response = await axios.get("http://127.0.0.1:8000/api/comments/?article=" + this.id); let tmp = response.data this.comments = tmp this.error = '' } catch(err) { this.error=err } } this is how it looks in django rest view -
Django LoginRequiredMixin not working as intented
The LoginRequiredMixin is not working as intended for the class based view below, I was able to access the webpage regardless of login status, but it should have redirected the unauthorized users to the login page. Where have I gone wrong? from django.shortcuts import render, redirect from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic import FormView from .forms import UpdatePortfolio # Create your views here. class UpdatePortfolioView(LoginRequiredMixin, FormView): login_url = 'users:login' redirect_field_name = 'mainpage:update' form = UpdatePortfolio template_name = 'mainpage/updateportfolio.html' def get_object(self): # return self.request.user.id return self.request.user.pk def get(self, request, *args, **kwargs): form = self.form_class return render(request, self.template_name, {'form': form}) -
django-river: example of change in state from a view
I am trying to use django-river to track and control the flow of objects in my application. In particular, I have objects representing document that will pass from the author to a reviewer and then on to a production team, ideally based on a view controlled by a button press. I was intending to have an owner field that could be changed to indicate who currently 'has' the document. Can someone please give me a short example of how this might work? Thank you! -
Two models have a foreign key to a third model - can I make an inline based on that foreign key?
While designing Django admin panel, I recently stumbled upon a following situation: I have three models: class A(models.Model): id_a = models.AutoField(primary_key=True) some_data = models.CharField(max_length=255, blank=True, null=True) id_c = models.ForeignKey('C', models.PROTECT, db_column='id_c') class B(models.Model): id_b = models.AutoField(primary_key=True) some_data = models.CharField(max_length=255, blank=True, null=True) id_c = models.ForeignKey('C', models.PROTECT, db_column='id_c') class C(models.Model): id_c = models.AutoField(primary_key=True) some_data = models.CharField(max_length=255, blank=True, null=True) As you can see, two of the models have a foreign key to the third. What i need to do is to create inline of model B in model A. It should be possible, since they share a foreign key to model C. (So what I want is: when I look at entity of model A in admin panel, I should have inlines of all the B entities, that have the same 'id_c', as the A entity I'm looking at.) So i tried it like this (in admin.py): class InlineB(admin.StackedInline): model = B extra = 1 @admin.register(A) class AdminPanel_A(SimpleHistoryAdmin): list_display = ['some_data'] inlines = [InlineB] But when doing it like this I get the error: B has no ForeignKey to A. Which of course is true, but those two models do have a ForeignKey in common, which I'm sure could be used to make … -
Django DRF how to validate captcha response for server side
I amusing nextjs as my frontend. I am struggling to validate server site captcha response. I want data will be not inserted in my database until captcha verification sucess. I tried drf-recaptcha package. Here is my code: settings.py INSTALLED_APPS = ['rest_framework_recaptcha',] #included in my installed app DRF_RECAPTCHA_SECRET_KEY = '< my_secrect key>' serializers.py from rest_framework_recaptcha import ReCaptchaField class ContactSerializer(serializers.ModelSerializer): recaptcha = ReCaptchaField() class Meta: model = Contact fields = '__all__' my API views.py @api_view(['POST', 'GET']) def contact_forms_api(request): if request.method == 'POST': ''' Begin reCAPTCHA validation ''' recaptcha_response = request.POST.get('g-recaptcha-response') url = 'https://www.google.com/recaptcha/api/siteverify' values = { 'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY, 'response': recaptcha_response } data = urllib.urlencode(values) req = urllib2.Request(url, data) response = urllib2.urlopen(req) result = json.load(response) ''' End reCAPTCHA validation ''' if result['success']: data = request.data serializer = ContactSerializer(data=data) if serializer.is_valid(): serializer.save() print(serializer.data) return Response({ 'status': True, 'message': 'sucess' }) return Response({ 'status': False, 'message': serializer.errors }) here is my nexjs code: I am using this package in my frontend application. here my code sometings look like: <form onSubmit={SubmitContact}> <input type="text"/> <ReCAPTCHA sitekey="my_captcha site ke=y" onChange={handleRecaptcha} /> <form> here is my SubmitContact function look like this: const res = await axios.post(url,data,{headers: headers} ) -
Django - Async views (api requests) and AJAX
I've used this code right here to speed up the api response of IEX. iex_var2 and iex_var1 and result are imported. I've also a form for the user where he searches for the ticker (input_ticker) The response works fine and is quit fast. async def api_test2(request): start_time = time.time() async with aiohttp.ClientSession() as session: input_ticker = request.POST['ticker'] for i in iex_var2: var2 = i url = f"{iex_var1}{input_ticker}{var2}" async with session.get(url) as res: url = await res.json() result.append(url) total = time.time() - start_time print(total) return HttpResponse(result) Now I've got two important questions about my code. How do I avoid, that each reload runs that code again? When I reload the HttpResponse, the view runs again and so on there is duplicated data in "result". Can I use a Cache herefor? I am still a beginner, probably mixing something up here? My question nr.2 is how to print this result into a template? Render does not work along with an async view, so I think AJAX is the solution, but I have neither experience with JS nor with AJAX. So I am not sure how I can the connect the "result" of my view with a template. I#ve also tried to use … -
Django redis docker
I want to make a chat app with django channels and I follow the steps from the docs. To enable the redis server you need to run docker run -p 6379:6379 -d redis:5 but when I run it I get: Unable to find image 'redis:5' locally docker: Error response from daemon: Head "https://registry-1.docker.io/v2/library/redis/manifests/5": Get "https://auth.docker.io/token?scope=repository%3Alibrary%2Fredis%3Apull&service=registry.docker.io": net/http: request canceled (Client.Timeout exceeded while awaiting headers). See 'docker run --help'. What should I do? Thanks,. -
Django get request divide to 3 branches?
I have an article list class (class ArticleListView(View):) In that class I want to have 1 get function with 3 different request. First one use for search articles Second one use for returning a random article link Third one return list of article I can do 2 different get request (all and search one) but I can not add third one. Is this technically possible and if yes who do I like to random page and what part of my get function is wrong? my code : class ArticleListView(View): template_name = "wiki/article_list.html" def get(self, request) : strval = request.GET.keys() if request.GET.get('search') : # Simple title-only search # objects = Post.objects.filter(title__contains=strval).select_related().order_by('-updated_at')[:10] # Multi-field search # __icontains for case-insensitive search query = Q(title__icontains=strval) query.add(Q(text__icontains=strval), Q.OR) article_list = Article.objects.filter(query).select_related().order_by('-updated_at')[:10] elif request.GET.get('random'): # find the number of article abject numberOfArticle = Article.objects.all().count() # find a random number from 1 to number of articles randomPK = random.randint(1, numberOfArticle) # filter article list object base on primary key ( pass that random number) #Item.objects.all()[0].type_id article_list = Article.objects.get(pk=randomPK) else : article_list = Article.objects.all().order_by('-updated_at')[:10] # Augment the article_list for obj in article_list: obj.natural_updated = naturaltime(obj.updated_at) ctx = {'article_list' : article_list, 'search': strval, 'random':strval} return render(request, self.template_name, ctx) my … -
How to properly display all inline fields associated with its parent model fields when paginating in Django template?
I'm a student and a Django newbie, and we have a project that we're trying to build using Django. In my journey to building the project I stumbled upon a problem and got stuck for weeks now. I want to display all the inline fields associated with its parent field on one page as I paginate. When I tried to paginate a model with 2 additional models that have foreign keys to it I got a weird result in my template. I can't seem to figure out how to fix it. I tried several methods on the Internet and have read numerous forums and discussions but to no avail, none has worked so far. Below are my files and a few Images: (models.py) from django.db import models class History(models.Model): BARANGAY = ( ('Alegria','Alegria'), ('Bagacay','Bagacay'), ('Baluntay','Baluntay'), ('Datal Anggas','Datal Anggas'), ('Domolok','Domolok'), ('Kawas','Kawas'), ('Ladol','Ladol'), ('Maribulan','Maribulan'), ('Pag-Asa','Pag-Asa'), ('Paraiso','Paraiso'), ('Poblacion','Poblacion'), ('Spring','Spring'), ('Tokawal','Tokawal') ) barangay_name = models.CharField(max_length=100,choices=BARANGAY,default='Alegria') barangay_img = models.ImageField(upload_to='history_imgs',blank=True) barangay_info = models.TextField() class GeoHazard(models.Model): history = models.ForeignKey(History,related_name='geohazards',on_delete=models.CASCADE) geohazard_img = models.ImageField(upload_to='history_imgs',blank=True) date_published = models.CharField(max_length=100, null=True) geohazard_info = models.TextField() class Assessment(models.Model): RATINGS = ( ('HIGH','HIGH'), ('HIGH (Mitigated)','HIGH (Mitigated)'), ('MODERATE','MODERATE'), ('MODERATE (Mitigated)','MODERATE (Mitigated)'), ('LOW','LOW'), ('UNKNOWN','UNKNOWN'), ) history = models.ForeignKey(History,related_name='assessment',on_delete=models.CASCADE) purok_name = models.CharField(max_length=50) purok_coordinates = models.CharField(max_length=100,default='unknown') flood_rating = models.CharField(max_length=100,choices=RATINGS,default='UNKNOWN') … -
How to get variable from POST method in Modelchoicefield
#forms class ChoiceAddressForm(forms.Form): choice_address = forms.ModelChoiceField(queryset=Address.objects.none(), empty_label='') #views def packing_create(request): if request.method == 'POST': choice_address_form = ChoiceAddressForm(request.POST) choice_address = choice_address_form.fields['choice_address'] return render(request, 'shop/packingcreate.html', {'choice_address': choice_address}) address = Address.objects.filter(usr_adr=request.user).values('adr_no', 'custom_name').order_by('adr_no') address = [tuple(i.values()) for i in address] choice_address_form = ChoiceAddressForm() choice_address_form.fields['choice_address'].choices = address return render(request, 'shop/packingcreate.html', {'choice_address_form': choice_address_form}) This is what I get: <django.forms.models.ModelChoiceField object at 0x7f1f2e6e1460> Also is_valid and cleaned_date not working. -
How to pass "self" or Page.id to a custom admin Panel in the Wagtail CMS?
More generally speaking I want add a custom admin Panel to list some related content. To lookup this related content I need to pass the current instance of the model or at least its ID to this panel. How can I do that within these lists in which these admin panels are noted? Here is my specific example of an ArtistPage. In the editor I would like to add a panel to list WorkPages that are related to this ArtistPage: from wagtail.models import Page class ArtistPage(Page): # ... content_panels = [ # ... ListWorksPanel(artist=self), # This doesn’t work ] The panel itself is defined like that, mostly copied from the HelpPanel: from wagtail.admin.panels import Panel class ListWorksPanel(Panel): def __init__(self, artist="", template="admin/list_works_panel.html", **kwargs,): super().__init__(**kwargs) self.artist = artist self.template = template def clone_kwargs(self): kwargs = super().clone_kwargs() del kwargs["help_text"] kwargs.update( artist=self.artist, template=self.template, ) return kwargs class BoundPanel(Panel.BoundPanel): def __init__(self, panel, instance, request, form): super().__init__(panel, instance, request, form) self.template_name = self.panel.template self.artist = self.panel.artist This is more a general Python question, I think. I know how to pass "self" in functions. But how does that work here with this class as element of a list? I reckon that the __init__() method of the ArtistPage … -
Database content doesn show on production
I am struggling to understand what is missing on my application, sorry it seems a little silly question, I am sure is something quite simple that I am not actually looking to. I have created an API, using REST-FRAMEWORK on my machine and upload it to production, but the content of my database didn't come through. If you see in the picture the product list appers as empty But on my machine it actually has some information -
Ajax post request fails without showing an error, it just prints an empty error
I am trying to create An ajax request in the Django template .. it fails and returns an empty error so am not even able to debug it. Here is what I tried to do : HTML template ..... kml_layer.addListener('click', (kmlEvent) => { setMapOnAll(null); var clickedPoint = kmlEvent.latLng; newPoint.postMessage(clickedPoint.lat() + "," + clickedPoint.lng()); $.ajax({ type: "POST", url: "https://www.{{domain}}{% url 'get_km_from_source' %}", data: { csrfmiddlewaretoken: '{% csrf_token %}', layer_id: "{{ single_layer.id }}", the_element_string_id: kmlEvent.featureData.id, clicked_lat: kmlEvent.latLng.lat, clicked_lng: kmlEvent.latLng.lng }, /* Passing the text data */ success: function (response) { alert("Thankyou for reaching us out " + response); }, error: function (jqXHR, textStatus, errorThrown) { // alert the error if any error occured console.log(textStatus, errorThrown); } }); }); ..... And here is the URL that is being called. path('get_km_from_source/', get_km_from_source, name='get_km_from_source'), Using print debugging in the python function that is being called.. it never reaches this point. but it always fails before starting the request .. and it returns an empty based on the lin console.log(textStatus, errorThrown); .. here is how the error looks like : console output: "error " -
Django Rest Framework: while using generics APIview I'm not able to set permissions
I want the admin user to access every user detail and the non-admin user to get access to its own detail only but Instead of this non-admin user is showing the full list of every user same as the admin user while implementing this. As I've shared my views.py, permissions.py, and models.py for the same. I'm not sure whether the problem is in permisions.py or models.py as I'm new to Django. I'm using Postman for API testing and this is working fine for the admin user but for an individual user, it's not working. views.py class UserListCreateAPIView(generics.ListCreateAPIView): permission_classes = [IsStaffOrTargetUser] queryset = User.objects.all() serializer_class = UserSerializer class UserRetrtieveUpdateDestroyAPIView(generics.RetrieveUpdateDestroyAPIView): permission_classes = [IsStaffOrTargetUser] queryset = User.objects.all() serializer_class = UserSerializer permissions.py class IsStaffOrTargetUser(BasePermission): def has_permission(self, request, view): # allow user to list all users if logged in user is staff return request.user or request.user.is_staff def has_object_permission(self, request, view, obj): # allow logged in user to view own details, allows staff to view all records return request.user.is_staff or obj == request.user models.py class User(AbstractBaseUser): email = models.EmailField(verbose_name='Email',max_length=255,unique=True) name = models.CharField(max_length=200) contact_number= models.IntegerField() gender = models.IntegerField(choices=GENDER_CHOICES) address= models.CharField(max_length=100) state=models.CharField(max_length=100) city=models.CharField(max_length=100) country=models.CharField(max_length=100) pincode= models.IntegerField() dob = models.DateField(null= True) # is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_admin … -
Adding a range price filter
I'm trying to add a range price filter for a list of products with django and I'm having some trouble with how to proceed Here's the code for the template : ( produits.html ) <div class="mb-4"> <h3 class="mb-3 h6 text-uppercase text-black d-block">Filter by Price</h3> <div id="slider-range" class="border-primary"></div> <input type="text" name="PRICE" id="amount" class="form-control border-0 pl-0 bg-white" disabled="" /> Here's the model code for products : class Product(models.Model): nom = models.CharField(max_length=200,null= True, blank=True) prix = models.DecimalField(max_digits=7,decimal_places=2,null=True,blank=True) description = models.TextField(null=True,blank=True) nbr_stock = models.IntegerField(null=True,blank=True,default=0) image= models.ImageField(null=True,blank=True) taille= models.CharField(max_length=5,null=True,blank=True) categorie=models.CharField(max_length=200,null= True, blank=True) @property def imageURL(self): try : url = self.image.url except : url = '' return url def __str__(self): return self.nom My question is how can I "retrieve" the value from the range slider and then show the products according to the price? thank you in advance