Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Filter birthday with less than 60 months Django
model.py class Preschooler(Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) birthday = models.DateField(null=True, blank=True) def age_months(self): today = date.today() date_diff = today - self.birthday in_days = date_diff.days return int((in_days) / (365 / 12)) I want to filter preschooler that are less than 60 months using their birthday like this: Preschooler.objects.filter(birthday__month__lst=60) How can I achieve this? Thank you. -
Using jinja variable as dictionary key
I'm making a django app to do with tests/exams. Two of the models in this app are the "Question" and "Answer" model which have a one-to-many relationship. On the page, each question will be listed with all of its possible answers below it which the user can choose from. In my views.py file, after getting the list of question objects, the best way I thought of for storing the answers was in a dictionary like so: answers = {} for question in questions: answers[question.id] = Answer.objects.filter(question=question.id) Then, for the template, I thought I would be able to do something like: {% for question in questions %} <h2>{{ question.title }}</h2> <ul> {% for answer in answers.{{ question.id }} %} <li>{{ answer.title }}</li> {% endfor %} </ul> {% endfor %} The error arises in this line - {% for answer in answers.{{ question.id }} %}. I've tried rewriting this line as per this post which suggested things like: {% for answer in answers[question.id] %} and {% for answer in answers.get(question.id) %} but none of these worked. Please let me know if there is a syntax in Jinja that allows this or else if there is a better way of me passing the … -
Saving multiple data entries to database with Django
in my project that I created with django, I duplicate the data entries with the help of a button, but when I want to save them to the database, it always saves the last added data. models.py medications = models.CharField(max_length=200, null=True,blank=True) scale_used = models.CharField(max_length=200, null=True,blank=True) views.py if request.method == "POST" and 'registrationSave' in request.POST: records = Records() records.medications = request.form.getlist('medications[]') records.scale_used = request.form.getlist('scale_used[]') print(records.medications) print(records.scale_used) records.save() return redirect('/index/tables') else: return render(request,'registration_form.html') registration.html <div class="row" id="InputsWrapper"> <div class="row justify-content-start"> <div class="col-4"> <!-- <textarea type="text" class="form-control" id="record_medications" name="medications" style="height: 100px" placeholder="İlaçlar" required></textarea> --> <label for="">İlaç Adı:</label> <select class="form-select form-select-lg" name="medications[]" id="medications"> <option>Lütfen İlaç Seçiniz</option> {% if medicationName%} {% for medicationName in medicationName %} <option value="{{medicationName.medicationName}}">{{medicationName.medicationName}}</option> {%endfor%} {%endif%} </select> </div> <div class="col-4"> <label for="scale_used" class="form-label">Kullanılan Ölçek</label> <input type="text" class="form-control" id="scale_used" name="scale_used[]"> </div> <div class="col-4"> </br> <button type="button" class="btn btn-primary" id="add_medications">İlaç Ekle+</button> </div> </div> </div> <script> $(document).ready(function() { var MaxInputs = 20; var InputsWrapper =$("#InputsWrapper"); var AddButton =$("#add_medications"); var x = InputsWrapper.length; var FieldCount = 1; $(AddButton).click(function(e) { if(x <= MaxInputs) { FieldCount++; $(InputsWrapper).append('<div class="row justify-content-start"><div class="col-4"><label for="">İlaç Adı:</label><select class="form-select form-select-lg" name="medications[]" id="medications_'+FieldCount+'"><option>Lütfen İlaç Seçiniz</option>{% if medicationName%}{% for medicationName in medicationName %}<option value="{{medicationName.medicationName}}">{{medicationName.medicationName}}</option>{%endfor%}{%endif%}</select></div><div class="col-4"><label for="scale_used" class="form-label">Kullanılan Ölçek</label><input type="text" class="form-control" id="scale_used_'+FieldCount+'" name="scale_used[]"></div></div>'); x++; } return … -
Django querry set SQL
in want and equivalent of this sql query in Django SELECT Gender, ServCode FROM [openimisproductTestDb_16_08_22].[dbo].[tblInsuree] JOIN [openimisproductTestDb_16_08_22].[dbo].[tblServices] ON [openimisproductTestDb_16_08_22].[dbo].[tblInsuree].AuditUserID = [openimisproductTestDb_16_08_22].[dbo].[tblServices].AuditUserID WHERE Gender = 'F' AND ServCode = 'F4' THIS IS THE MODEL ` def assisted_birth_with_cs_query(user, **kwargs): date_from = kwargs.get("date_from") date_to = kwargs.get("date_to") hflocation = kwargs.get("hflocation") format = "%Y-%m-%d" date_from_object = datetime.datetime.strptime(date_from, format) date_from_str = date_from_object.strftime("%d/%m/%Y") date_to_object = datetime.datetime.strptime(date_to, format) date_to_str = date_to_object.strftime("%d/%m/%Y") dictBase = { "dateFrom": date_from_str, "dateTo": date_to_str, } dictGeo = {} if hflocation and hflocation!="0" : hflocationObj = HealthFacility.objects.filter( code=hflocation, validity_to__isnull=True ).first() dictBase["fosa"] = hflocationObj.name claimItem = Insuree.objects.filter( validity_from__gte = date_from, validity_to__lte = date_to, **dictGeo, gender = 'F' ).count() data = Service.objects.filter(code = 'F4').count() | Insuree.objects.filter(gender = 'F').count() dictGeo['health_facility'] = hflocationObj.id dictBase["post"]= str(data) return dictBase ` I tried like that but the one just adds when I want the women included in the insured table and the F4 code contained in the service table. both tables have the auditUserID column in common -
How can i not set <pk> at my url to get certain data?
I am trying to not set str:pk behind my url while updating or deleteing certain data with restframework ` class BarrelAPIView(APIView): def get(self,request): barrel = Barrel.objects.all() #queryset serializer = BarrelSerializer(barrel, many=True) return Response(serializer.data) def post(self,request): serializer = BarrelSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self,request): try: data = request.data Barrel.objects.filter(code=data['code']).delete() return Response(status=status.HTTP_204_NO_CONTENT) except Exception as error: return Response( status=status.HTTP_400_BAD_REQUEST) ` it can be done on postman by passing the 'code'. but when i try on restframework default api browser the delete button showed up but nothing happen after that -
Javascript keeps repeating itself [closed]
I have a js that shows the previews of images before there upload after the frst image is inputted the sceond image gets doubled and the third images gets trippled and so it continues I honestly don't know what am not so god with js -
Django JSONField query error: operator does not exist: jsonb = bigint
Let's say I have 2 tables A and B. Table B has a JSON field named preferences which contains a field with id of table A called a_id. I want to count number of B rows which refers to A table rows like this: A.objects.annotate(count=Count(B.objects.filter(preferences__a_id=OuterRef('id')))) However, I get an error that operator does not exist: jsonb = bigint. According to this answer, I should be able to refer to JSON field attributes using two underscores (__) between names. Why doesn't it work in my case? -
How to prevent template from reloading with Ajax?
I have two forms and two submit buttons and two textareas. The situation is that if I uplaod the content to one textaarea the content of other texarea will be lost because of reloading. So that is why I try to implement Ajax. So I have it like this: <body> <div class="container center"> <span class="form-inline" role="form"> <div class="inline-div"> <form class="form-inline" role="form" action="/controlepunt140" method="POST" enctype="multipart/form-data" id="form_pdf" > <div class="form-group"> {% csrf_token %} {{ form }} <button type="submit" name="form_pdf" class="btn btn-warning"> Upload! </button> </div> </form> <div class="form-outline"> <div class="form-group"> <textarea class="inline-txtarea form-control" cols="70" rows="25"> {{content}}</textarea > </div> </div> </div> </span> <span class="form-inline" role="form"> <div class="inline-div"> <form class="form-inline" role="form" action="/controlepunt140" method="POST" enctype="multipart/form-data" id="form_excel" > <div class="form-group"> {% csrf_token %} {{ form }} <button type="submit" name="form_excel" class="btn btn-warning"> Upload! </button> </div> </form> <div class="form-outline"> <div class="form-group"> <textarea class="inline-txtarea form-control" cols="65" rows="25"> {{content_excel}}</textarea > </div> </div> </div> </span> </div> <script type="text/javascript"> $("#form_pdf").submit(function (e) { $.ajax({ url: "/controlepunt140", type: "POST", data: new FormData(this), processData: false, contentType: false, success: function (result) { console.log(result); }, }); e.preventDefault(); }); $("#form_excel").submit(function (e) { $.ajax({ url: "/controlepunt140", type: "POST", data: new FormData(this), processData: false, contentType: false, success: function (result) { console.log(result); }, }); e.preventDefault(); }); </script> </body> But then I get … -
Is there better way to check if optional keys are in a list?
I am looking for a better way to handle optional data in a request. I have to check wheter the optional parameters are filled and them insert them in a django model. This picture shows what i have got so far enter image description here I need to add more keys and i do not want to end up adding hundreds of those lines in my project. I have tried to do something like for key in data: if key in django_model: (tried to use the meta classes) local_listing[key] = data[key] this did not work, because a django model is not a simple list. How can i do better? -
Jquery datepicker not working after submitting form in django app
I have a Django app with some views that contain a jquery datepicker. The page shows invoices for a specific month (present month by default) and the user can change it any month he wants with the datepicker. That works. The problem is if the user wants to see another month, when he clicks the datepicker for the second time, nothing happens. {% extends 'base_layout.html' %} {% block content %} <div class="row"> <div class="supplier_search"> <form method="POST"> {% csrf_token %} <label for="startDate">month: </label> <input name="startDate" id="startDate" autocomplete="off" /> <input class="list_button" type="submit" value="show" /> <button onclick="send_to_accountant()">send to accountant</button> </form> </div> </div> <div class="select-month"> </div> <div class="invoices_list"> <table id="invoice_list_table"> <tr> <th>invouce number</th> <th>company</th> <th>phone</th> <th>mail</th> <th>amt</th> <th>amt with vat</th> </tr> {% for inv in invoices %} <tr> <td> <a href="{{inv.invoice_file.url}}" target="_blank">{{ inv.invoice_number }}</a> </td> <td> {{ inv.supplier.company_name }} </td> <td> {{ inv.supplier.company_phone_nr }} </td> <td> {{ inv.supplier.company_email }} </td> <td> {{ inv.total_without_vat }} </td> <td> {{ inv.total_vat_included }} </td> </tr> {% endfor %} </table> </div> {% endblock %} {% block jsscript %} <script> function send_to_accountant(){ var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val(); var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val(); month_year = month + ' ' + year var url = "{% url 'invoice:send_to_accountant' %}"; var … -
ODBC Driver 17 for SQL Server Login timeout expired (0)
Getting the above mentioned error while running the migrate a django api app which requires creating a database in sql server. I am running on mac computer. My setting.py file: DATABASES = { "default": { 'ENGINE': 'mssql', 'NAME': str(os.getenv("DB_NAME")), # 'mytestdb', 'HOST': str(os.getenv("DB_SERVER")), # <server name> 'PORT': 1433, # <port> 'USER': str(os.getenv("DB_USER")), # <username> 'PASSWORD': str(os.getenv("DB_PASSWORD")), # <password> 'Trusted_Connection': 'no', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', 'isolation_level':'READ UNCOMMITTED', #to prevent deadlocks }, } } My Django version: 4.0.8 My Python version: 3.10.7 Please ley me know if more info is required. Very naive to coding! I have installed the driver following text Microsoft instructions. My pyodbc version: 4.0.34 To connect to MS SQL Server from python app. Please ley me know if more info is required. Very naive to coding! -
Shopify webhook request verification for `orders/create` topic returning False in python/django project
I am trying to verify a Shopify webhook request for the topic orders/create, but the verification is returning False, I am not able to figure out the reason. Here's the code snippet I am using to verify the request. views.py class ShopifyWebhookOrderCreate(APIView): def post(self, request): verified = verify_webhook(request.body, request.META.get('HTTP_X_SHOPIFY_HMAC_SHA256')) if not verified: return Response(status=status.HTTP_401_UNAUTHORIZED) ... ... ... and for verifying the request I am doing this:- def verify_webhook(data, hmac_header): CLIENT_SECRET = config('SHOPIFY_CLIENT_SECRET') digest = hmac.new(CLIENT_SECRET.encode('utf-8'), data, digestmod=hashlib.sha256).digest() computed_hmac = base64.b64encode(digest) return hmac.compare_digest(computed_hmac, hmac_header.encode('utf-8')) request.body format is b'{'the': 'data'}' I verified the SECRET with the Shopify app. -
get_object_or_404() got an unexpected keyword argument 'slug'
TypeError at /vegetables/ get_object_or_404() got an unexpected keyword argument 'slug' views.py from django.shortcuts import render, get_object_or_404 from .models import Category from .models import Product def allProductCategory(request,c_slug=None): c_page=None products=None if c_slug!=None: c_page=get_object_or_404(Category,slug=c_slug) products=Product.objects.all().filter(category=c_page,available=True) else: products=Product.objects.all().filter(available=True) return render(request, 'category.html',{'category':c_page,'products':products}) urls.py from django.contrib import admin from . import views from django.urls import path,include app_name='ecommerceapp' urlpatterns = [ path('',views.allProductCategory,name='allProductCategory'), path('<slug:c_slug>/',views.allProductCategory,name='products_by_category'), ] I'am getting this error when I click on the hyperlink vegetables and cotton dress. -
Annotations Force Cached Queryset Evaluation
I am having issues using cache with annotate. When I run annotate, the queryset is evaluated, ignoring the cached results. This makes it much slower. I’d like to be able to annotate my model without having to fully run the query. Is this possible? If not, why not? from django.core.cache import cache from django.db.models import Exists, OuterRef favorites = Favorites.objects.filter(item = OuterRef(‘pk’), user=user) best_items = cache.get(‘best_items’) best_items = best_items.annotate(is_favorite= Exists(favorites)) -
Get max Value with Distinct Foreign key Django ORM
So this is my Model. class OrderLine(models.Model): product = models.ForeignKey(Product, on_delete=models.PROTECT, verbose_name="Product", null=False) unit_price = models.DecimalField(null=True, max_digits=12, decimal_places=4, blank=True, verbose_name="Unit price") Im trying to filter with Multiple Product Ids, One product can have multiple OrderLine with different Unit price.So how can i fetch one record of Max Unit price for Each product. I tried aggregate(Max("unit_price")) But it returns one over all the products. -
TemplateDoesNotExist at / Exception Value: index.html django
welcome i make a new project and i put index.html in templates dirctory and when i runserver i got the message TemplateDoesNotExist at / where the mistake i done there is the views.py from django.shortcuts import render, redirect def index(request): return render(request,'index.html') there is the urls.py from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.index,name='index'), ] and there is the sitting.py import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent TEMPLATES_DIR = os.path.join(BASE_DIR, 'templates') STATIC_DIR = os.path.join(BASE_DIR, 'static') the templates_dir and static_dir i add it after make project -
How to pass a calendar in a generic form with a request?
Can you please tell me how to transfer the calendar to the form with a get request, with clicking on the days of the week and transferring to the form? There is a filtering for all fields at the same time now, only with the date of trouble ( Approximately how such a calendar can be transmitted? Thanks in advance. class Traveller(models.Model): title = models.CharField(max_length=30,default='',null=False) origin = models.ForeignKey(Origin,on_delete=models.CASCADE,max_length=100,verbose_name= 'Источник',default='') destination = models.ForeignKey(Destination,on_delete=models.CASCADE, verbose_name="Местонахождение",default='') transport = models.ForeignKey(Transport,on_delete=models.CASCADE, verbose_name="Транспорт",default='') passengers = models.ForeignKey(Passengers,on_delete=models.CASCADE, verbose_name="Пассажиры",default='') url = models.SlugField(max_length=130, unique=True) def __str__(self): return self.title class Meta: verbose_name = 'Путешествие' verbose_name_plural = 'Путешествие' def get_absolute_url(self): return reverse("traveller", kwargs={"url": self.url}) `views: class FullTraveller: def get_origin(self): return Origin.objects.all() def get_destination(self): return Destination.objects.all() def get_transport(self): return Transport.objects.all() def get_passengers(self): return Passengers.objects.all() class TravellerView(FullTraveller, ListView): template_name = 'index.html' model = Traveller queryset = Traveller.objects.all() paginate_by = 1 class FilterTravelView(FullTraveller,ListView): def get_queryset(self): if self.request.GET.getlist("origin") and self.request.GET.getlist("destination") and self.request.GET.getlist( "transport") and self.request.GET.getlist("destination"): queryset = Traveller.objects.filter(origin__in=self.request.GET.getlist("origin"), destination__in=self.request.GET.getlist("destination"), transport__in=self.request.GET.getlist("transport"), passengers__in=self.request.GET.getlist("passengers")) else: queryset = Traveller.objects.filter(Q(origin__in=self.request.GET.getlist("origin")) | Q( destination__in=self.request.GET.getlist("destination")) | Q( transport__in=self.request.GET.getlist("transport"))| Q( passengers__in=self.request.GET.getlist("passengers"))) return queryset def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context["origin"] = ''.join([f"origin={x}&" for x in self.request.GET.getlist("origin")]) context["destination"] = ''.join([f"destination={x}&" for x in self.request.GET.getlist("destination")]) context["transport"] = ''.join([f"transport={x}&" for x in self.request.GET.getlist("transport")]) context["passengers"] … -
Getting fields from extra manager methods using django-rest-framework
I have the following custom model manager in Django that is meant to count the number of related comments and add them to the objects query set: class PublicationManager(models.Manager): def with_counts(self): return self.annotate( count_comments=Coalesce(models.Count('comment'), 0) ) Adding this manager to the model does not automatically add the extra field in DRF. In my API view, I found a way to retrieve the count_comments field by overriding the get function such as: class PublicationDetails(generics.RetrieveUpdateAPIView): queryset = Publication.objects.with_counts() ... def get(self, request, pk): queryset = self.get_queryset() serializer = self.serializer_class(queryset.get(id=pk)) data = {**serializer.data} data['count_comments'] = queryset.get(id=pk).count_comments return Response(data) This works for a single instance, but when I try to apply this to a paginated list view using pagination_class, overriding the get method seems to remove pagination functionality (i.e. I get a list of results instead of the usual page object with previous, next, etc.). This leads me to believe I'm doing something wrong: should I be adding the custom manager's extra field to the serializer instead? I'm not sure how to proceed given that I'm using a model serializer. Should I be using a basic serializer? -
How can I display total likes per month of an post to the author on Django
I want to display total likes a author got on his post on monthly basis in Django. For eg: On january total likes of his post is like 100 def total_contents(self): total_likes_received = post.objects.filter(author=self.request.user).count() return total_likes_received def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['total_contents'] = self.total_contents() return context This is my views.py but this code will return total post he posted on the website. I want to return total likes he go on his post per month on Django class blogs(models.Model): title = models.CharField(max_length=100, null=True, blank=True) slug = models.SlugField(max_length=200, unique=True, auto_created=True) author = models.ForeignKey(User, on_delete=models.CASCADE) created_on = models.DateField(auto_now_add=True) time = models.TimeField(auto_now=True) likes = models.ManyToManyField(User, related_name='likes', blank=True) liked = models.BooleanField(default=False) like_count = models.BigIntegerField(default=0) post = models.TextField(max_length=200 ) -
Can't set multiple forign keys in one table in django models
Actually my code is like, Models.py class Employee(models.Model): employee_code = models.IntegerField(unique=True,primary_key=True) employee_name = models.CharField(max_length=50,unique=True) class LeaveRequest(models.Model): emp_name = models.ForeignKey(Employee, on_delete=models.CASCADE, related_name='empl_name') emp_code = models.ForeignKey(Employee, on_delete=models.CASCADE, related_name='emp_code',default='') leave_type = models.CharField(choices=( ('CL', 'Casual leave'), ('SL', 'Sick leave'), ('ML', 'Medical leave'), ('Comp off', 'Compensation') ),default='',max_length=20) serializers.py class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = '__all__' class LeaverequestSerializer(serializers.ModelSerializer): class Meta: model = LeaveRequest fields = '__all__' Views.py class Empcreate(CreateAPIView): # permission_classes = [IsAuthenticated] serializer_class = EmployeeSerializer def post(self, request): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response({ "user": serializer.data, "message": "User Created Successfully..!", }) class Leaverequest(CreateAPIView): serializer_class = LeaverequestSerializer def post(self, request): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response({ "user": serializer.data, "message": "Request Created Successfully..!", }) Actually since i mapped two foreign keys from same table(emp_name and code),there is the problem arriving. whenever i create request in leave request module, emp_name also showing emp_code as shown in the image below. But i want to display the name, can anyone suggest resolution for this, also how can i set different conditions for different leave types, where to create the conditions ? serializers or views? is for loop good option for creating different conditions of leave types? -
html h1 tag no show type
after click no.1 and blank to than page it no show h1 tag enter image description here inspect here enter image description here code html here {% extends "main.html" %} {% block content %} <h1>{{room.name}}</h1> {% endblock content %} code python here i don't know this have problem or not from django.shortcuts import render rooms = [ {'id': 1, 'name': 'Lets learn python!'}, {'id': 2, 'name': 'Design with me!'}, {'id': 3, 'name': 'Fronted develpoers!'}, ] def home(request): context = {'rooms': rooms} return render(request, 'base/home.html', context) def room(request, pk): room = None for i in rooms: if i['id'] == int(pk): room = i context = {'romm': room} return render(request, 'base/room.html', context) -
Django - Contain both register & login views on the same page
I am creating a simple application in Django, where my users can register and login to their accounts. I have both a signup and a login form on my home page, but it doesn't work for logging in or registering: the form won't let the user's create an account or sign into their already existing account. My Register Form: <form action = "" method = "POST"> {% csrf_token %} <input type="email" placeholder="Email" name = "email" /> <input type="text" placeholder="Username" name = "username" /> <input type="password" placeholder="Password" name = "password" /> <button type = "submit" name = "register">Register</button> </form> My login form: <form action = "" method = "POST"> {% csrf_token %} <input type="text" placeholder="Username" name = "username" /> <input type="password" placeholder="Password" name = "password" /> <button type = "submit" name = "login">Log In</button> </form> And finally, my view (I based it off [this](How can i Register and Login In The Same Page in Django? solution but it doesn't work): def home(request): if "register" in request.method == "POST": if request.method == "POST": email = request.POST.get('email') username = request.POST.get('username') password = request.POST.get('password') newuser = User.objects.create_user(username = username, email = email, password = password, ) newuser.save() user = authenticate(request, username=username, password=password) if "login" … -
How to show a detail view Serialize in a Django Project
In my Django Project I have Category and a SubCategory. Under each Category there are several SubCategory items. I want to show all the SubCategory items under the Category. I was able to show all the Category items under the same user, but not sure how to filter the SubCategory items that is related to same Category. Here are the models.py class Category(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class SubCategory(models.Model): category= models.ForeignKey(Category, on_delete=models.CASCADE, related_name='SubCategory') Here are the serializers.py class Categoryerializer(serializers.ModelSerializer): user = serializers.CharField(source="user.username", read_only=True) class Meta: model= Category fields = '__all__' class SubCategorySerializer(serializers.ModelSerializer): class Meta: model= SubCategory fields = '__all__' Here is the views: @api_view(['GET']) @permission_classes([AllowAny]) def getCategory(request, **kwargs): user = get_object_or_404(User, username=request.user) category =Category.objects.filter(user=user) serializer = categoryserializer(category, many=True) return Response(serializer.data) @api_view(['GET']) @permission_classes([AllowAny]) def getSubCategory(request, id,**kwargs): user = get_object_or_404(User, username=request.user) category =Category.objects.filter(user=user, id=id) subcategory =SubCategory.objects.filter(category_id=id) serializer = SubCategorySerializer(subcategory, many=True) return Response(serializer.data) Here are the urls: urlpatterns = [ path('<str:username>/category/', views.getCategory, name='api_category'), path('<str:username>/category_details/<int:id>', views.getSubCategory, name='api_subcategory'), My question how can I show the items of each SubCategory which is related to a specific Category -
Is there an up to date Django geolocation module that can give me countries using IP?
Is there something as simple as plug in the code and go for geolocation? I only want countries so that my website can switch to the appropriate language. It seems that the ones I found are either deprecated, have less than 10 users, are paid/trial versions. -
InvalidAlgorithmError in Django REST framework simplest
Does anybody how to solve this issue? from .backends import TokenBackend File "....../envs/jwt/lib/python3.9/site-packages/rest_framework_simplejwt/backends.py", line 7, in <module> from jwt import InvalidAlgorithmError, InvalidTokenError, algorithms ImportError: cannot import name 'InvalidAlgorithmError' from 'jwt' (...../drf-courses/jwt/jwt/__init__.py)