Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django serializer.save() gives back a HTTP 400 Bad Request
I have the following straightforward setup: a folder order with a models.py file, from django.contrib.auth.models import User from django.db import models from product.models import Product class Order(models.Model): user = models.ForeignKey(User, related_name='orders', on_delete=models.CASCADE) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) email = models.CharField(max_length=100) address = models.CharField(max_length=100) zipcode = models.CharField(max_length=100) place = models.CharField(max_length=100) phone = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True) paid_amount = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) stripe_token = models.CharField(max_length=100) class Meta: ordering = ['-created_at',] def __str__(self): return self.first_name class OrderItem(models.Model): order = models.ForeignKey(Order, related_name='items', on_delete=models.CASCADE) product = models.ForeignKey(Product, related_name='items', on_delete=models.CASCADE) price = models.DecimalField(max_digits=8, decimal_places=2) quantity = models.IntegerField(default=1) def __str__(self): return '%s' % self.id a serializers.py file from rest_framework import serializers from .models import Order, OrderItem class OrderItemSerializer(serializers.ModelSerializer): class Meta: model = OrderItem fields = [ "price", "product", "quantity", ] class OrderSerializer(serializers.ModelSerializer): items = OrderItemSerializer(many=True) class Meta: model = Order fields = [ "id", "first_name", "last_name", "email", "address", "zipcode", "place", "phone", "stripe_token", "items", ] def create(self, validated_data): items_data = validated_data.pop('items') order = Order.objects.create(**validated_data) for item_data in items_data: OrderItem.objects.create(order=order, **item_data) return order and finally, a views.py file import stripe from django.conf import settings # get secret key from rest_framework import status, authentication, permissions from rest_framework.decorators import api_view, authentication_classes, permission_classes from rest_framework.response import Response from .serializers import … -
Django chained dropdowns with ajax
I hope you are all doing well, I have implemented a Dependent / Chained Dropdown List for dropdown and it was working properly, but while I add the third one, it is not working well until reload the page. this is my try : here is the HTML code and the ajax script: <form method="post" id="studentForm" data-branches-url="{% url 'ajax_load_branches' %}" novalidate> {% csrf_token %} <table> {{ form.as_table }} </table> <button type="submit">Save</button> <a href="{% url 'student_changelist' %}">NevermiNnd</a> </form> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> $("#id_college").change(function () { var url = $("#studentForm").attr("data-branches-url"); var collegeId = $(this).val(); $.ajax({ url: url, data: { 'college': collegeId }, success: function (data) { $("#id_branch").html(data); } }); }); $("#id_branch").change(function () { var url = $("#studentForm").attr("data-reds-url"); var branchId = $(this).val(); $.ajax({ url: url, data: { 'branch': branchId }, success: function (data) { $("#id_red").html(data); } }); }); </script> form.py class StudentForm(forms.ModelForm): class Meta: model = Student fields = ('name', 'birthdate', 'college','branch','red') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['branch'].queryset = Branch.objects.none() self.fields['red'].queryset = Red.objects.none() if 'college' in self.data: try: college_id = int(self.data.get('college')) self.fields['branch'].queryset = Branch.objects.filter(college_id=college_id).order_by('name') except (ValueError, TypeError): pass # invalid input from the client; ignore and fallback to empty City queryset if self.instance.pk: self.fields['branch'].queryset = self.instance.college.branch_set.order_by('name') if 'branch'in self.data: try: branch_id = int(self.data.get('branch')) … -
Serialize pandas dataframe consists Nan fields before sending as a response
I have a dataframe that has Nan fields in it. I want to send this dataframe as a response. Because it has Nan fields I get this error, ValueError: Out of range float values are not JSON compliant I don't want to drop the fields or fill them with a character or etc. and the default response structure is ideal for my application. Here is my views.py ... forecast = forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']] forecast['actual_value'] = df['y'] # <- Nan fields are added here forecast.rename( columns={ 'ds': 'date', 'yhat': 'predictions', 'yhat_lower': 'lower_bound', 'yhat_upper': 'higher_bound' }, inplace=True ) context = { 'detail': forecast } return Response(context) Dataframe, date predictions lower_bound higher_bound actual_value 0 2022-07-23 06:31:41.362011 3.832143 -3.256209 10.358063 1.0 1 2022-07-23 06:31:50.437211 4.169004 -2.903518 10.566005 7.0 2 2022-07-28 14:20:05.000000 12.085815 5.267806 18.270929 20.0 ... 16 2022-08-09 15:07:23.000000 105.655997 99.017424 112.419991 NaN 17 2022-08-10 15:07:23.000000 115.347283 108.526287 122.152684 NaN Hoping to find a way to send dataframe as a response. -
How To Resolve MVT with Postgrse SQL Error?
just giving black screen error whenever try to connect or perform. Tried to map it again but not working. Installed Properly as well as showing reflection in terminal. -
Django Model Meta options - custom permissions no effect in production
I added custom permissions for Django's import-export library in the Model Meta options. Example from the documentation: class Task(models.Model): ... class Meta: permissions = [ ("change_task_status", "Can change the status of tasks"), ("close_task", "Can remove a task by setting its status as closed"), ] This works fine on the local server but in production there seems to be no effect when the permissions are applied to a user. The custom permissions can still be found in the permissions-list of the admin page for users and groups but when applied the user still can't see the import/export buttons. The according migration files ran fine when deploying. We use Django 3.1.2 and django-import-export 2.5.0. Has anyone ever had this problem before? Where are the Model meta options actually stored after the migration? Thanks in advance! -
DjangoRestFramework: Not able to set permissions for custom user model
I've created a custom user model in my project using an abstract base user but when I'm setting permissions for my User view it's giving me a field error. I wanted to set permission for Admin and Non-Admin users: (a) Admin user: It can access any user (View/edit). (b) Non-Admin user: It can access its own object (view/edit). so something like permission_classes = [IsUserOrIsAdmin] I've shared my corresponding model.py, serializers.py, view.py, permissions.py, and traceback for the same. I'm working on these 2 endpoints: path('customer/', UserListCreateAPIView.as_view()), path('customer_info/<int:pk>/', UserRetrtieveUpdateDestroyAPIView.as_view()), ***models.py*** import email from pyexpat import model from django.db import models from django.conf import settings from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser) GENDER_CHOICES = ( (0, 'male'), (1, 'female'), (2, 'not specified'),) class UserManager(BaseUserManager): def create_user(self, email, name,contact_number,gender,address,state,city,country,pincode,dob ,password=None, password2=None): """ Creates and saves a User with the given email, name, and password. """ if not email: raise ValueError('User must have an email address') user = self.model( email=self.normalize_email(email), name=name, contact_number=contact_number, gender=gender, address=address, state=state, city=city, country=country, pincode=pincode, dob=dob, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, name,contact_number,gender,address,state,city,country,pincode,dob , password=None): """ Creates and saves a superuser with the given email, name, and password. """ user = self.create_user( email, … -
django rest framework upload image to related model using generic.createAPIView
I am scheduling a medical camp at some destination. After reaching the destination i want to upload picture of that destination of mapped destination. I Created two model for that One is SiteMap class SiteMap(models.Model): MpId = models.IntegerField(verbose_name='MPID') VisitingDate = models.DateField(default=timezone.now,verbose_name='Date') Vehical = models.ForeignKey(VehicalMaster,on_delete=models.CASCADE,verbose_name='Vehical') Doctor = models.ForeignKey(User,on_delete=models.CASCADE,verbose_name='Doctor') District = models.ForeignKey(District,on_delete=models.CASCADE,verbose_name='District') Block = models.ForeignKey(Block,on_delete=models.CASCADE,verbose_name='Block') Panchayat = models.CharField(max_length=120,verbose_name="Panchayat") Village = models.CharField(max_length=120,verbose_name='Village') updated = models.DateTimeField(auto_now=True) And secod one is SiteMapImage class SiteMapImage(models.Model): MPID = models.ForeignKey(SiteMap,on_delete=models.CASCADE,verbose_name='MPID') SiteImage = models.ImageField(default='default.png',upload_to='sitemap/%Y/%m/%d') Location = models.CharField(max_length=200,verbose_name='Location',null=True,blank=True) Latitude = models.CharField(max_length=120,verbose_name='Latitude',null=True,blank=True) Longitue = models.CharField(max_length=120,verbose_name='Longitude',null=True,blank=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return f"{self.MPID}" def save(self): super().save() siteimg = Image.open(self.SiteImage.path) if siteimg.height>300 or siteimg.width>300: output_size = (300,300) siteimg.thumbnail(output_size) siteimg.save(self.SiteImage.path) I have created a serializer class for this. Here is the code. class SiteMapImageSerializer(serializers.ModelSerializer): class Meta: model = SiteMapImage fields = ['MPID','Location','Latitude','Longitue','SiteImage'] and this is my view.py class SiteMapImageCreateView(generics.CreateAPIView): lookup_field = 'SiteMap.pk' serializer_class = SiteMapImageSerializer def get_queryset(self): return SiteMapImage.objects.all() I don't know what wrong i did. but not working in broweser too. I upload the error image tooo. -
Highlighting current url not working with request resolver
I have the following urls from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('landing', views.landing, name='landing'), path('json', views.json, name='json'), path('bootstrap', views.bootstrap, name='bootstrap'), path('page', views.page, name='page'), ] I am using twitter bootstrap 5 and i want to highlight home when a user visits the landing page and append active when the current url matches <li class="nav-item"> <a href="{% url '' %}" class="nav-link {% if request.resolver_match.view_name == '' %}active{% endif %}">Home</a> </li> <li class="nav-item"> <a href="{% url 'page' %}" class="nav-link {% if request.resolver_match.view_name == 'page' %}active{% endif %}">Page</a> </li> I get this error django.urls.exceptions.NoReverseMatch: Reverse for '' not found. '' is not a valid view function or pattern name. Even when i replace the blank '' with 'landing' the active class is not appended.How can i correct this? -
Erros: Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
new to django django version : Django==2.2 getting below error : Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS while running below commands: python3.7 manage.py collectstatic python3.7 manage.py shell python3.7 manage.py runserver below is what my INSTALLED_APPS look like INSTALLED_APPS = ( 'actions.apps.MyAppConfig', 'common.apps.MyAppConfig', 'hotels.apps.MyAppConfig', 'extranet.apps.MyAppConfig', 'communication.apps.MyAppConfig', 'bulk_uploader.apps.MyAppConfig', 'registration.apps.MyAppConfig', 'channel_manager.apps.MyAppConfig', 'reports.apps.MyAppConfig', 'mobile.apps.MyAppConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'admin_shortcuts', 'guardian', 'actstream', 'rest_framework', 'django_filters', 'rest_framework.authtoken', 'oauth2app', 'ckeditor', 'stats', 'django_celery_beat', ) any suggestion? -
Calculation of input value and store it into database django
I want per unit price value according to input value and save it on database, I don't know how to do this task kindly help me plz model.py class Celldetail(models.Model): CellInvoiceNo = models.IntegerField(null=True, blank=True) Cell_Type = models.CharField(max_length=200, null=True) Cell_qty = models.DecimalField(default=0) Cell_price = models.DecimalField(default=0) Cell_PUP = models.FloatField() views.py def add_inventory_view(request): form = CellForm(request.POST or None) if form.is_valid(): form.save() context = { 'form': form, } return render(request, "addinventory.html", context) -
how to reload page in django using js2py?
i run script every 15 mins to update data on my website but i want to reload ppage in browser after update automatically i tried to put window.location.reload(true) using js2py and script looks like this: import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') import django django.setup() from django.core.management import call_command import time import js2py js = """ window.location.reload(true); """ def reload(): context = js2py.EvalJs() context.execute(js) while True: call_command("feed_update") reload() time.sleep(900) and i get error: raise MakeError('TypeError', js2py.internals.simplex.JsException: TypeError: Undefined and null dont have properties (tried getting property 'reload') -
Django blog page, admin page stopped working
I try to code a blog with Django and it worked pretty well until I couldn't open the admin page anymore: 127.0.0.1:8000/admin/. I created a superuser I could login to the admin page but then I changed something else but I can't say what. The blog with the database and my personal was working except the admin page. Do you have any idea why that happened? Appreciate any help. The following image shows the failure message: Here is my code: settings.py from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'xxx' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', 'ckeditor', 'ckeditor_uploader', 'taggit', 'django.contrib.sites', 'django.contrib.sitemaps', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'thomkell.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'thomkell.wsgi.application' # Database DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': … -
use create_serializer inside another create_serializer in drf
I've three models: class Person(models.Model): name = models.CharField(max_length=255) age = models.IntegerField() class OrganisationBenefits(models.Model): person = models.Foreignkey(Person, on_delete=models.CASCADE) benefits = models.CharField(max_length=255) class ProjectsInvolved(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) projects = models.CharField(max_length=255) I'm getting data from frontend as: { "name": "John Doe", "age": "30", "organisation_benefits": [ { "benefits": "dummy" }, { "benefits": "dummy" } ], "projects_involved": [ { "project": "dummy", }, { "project": "Dummy" } ]} I'm getting data(request.data) from my views into my serializer as validated_data. The serializer looks something like this: class PersonDetailsCreateSerializer(serializers.ModelSerializer): benefits = serializers.ListField(required=False) projects = serializers.ListField(required=False) class Meta: model = Person fields = '__all__' def create(self, validated_data): benefits = validated_data.pop('benefits') projects = validated_data.pop('projects') person = person.objects.create(**validated_data) for benefit in benefits: benefit.update({'person': person}) serializer_benefit = BenefitCreateSerializer(data=benefits, many=True) if serializer.is_valid(): serializer.save() for project in projects: project.update({'person': person}) serializer_project = ProjectCreateSerializer(data=projects, many=True) if serialzer_project.is_valid(): serializer_project.save() return person Is this the right approach? Because only person instance is getting created but not benefits and projects. I'm not even sure if I can call another create serializer inside def create() of another serializer. I'm confused at this moment. Instead of this, when I use a for loop and call Model_name.objects.create(), its working as per my expectations. But don't want to user a for … -
How to exclude certain hours between two date differenece?
I want to get the total hours difference between two timestamps but I want to exclude certain hour in there . I want to exclude these hours from 5PM-10AM everyday. from datetime import datetime def get_total_hours(model_instance): datetime = model_instance.datetime now = datetime.now() diff = now - datetime total_secs = diff.total_seconds() hours = total_secs // 3600 return hours -
How to get request host in django?
How to get request host in django ? how will I get host URL/name from request class StoreLocations(APIView): """ GET : For fetching store locations Returns : Store Locations --------------- json """ permission_classes = [] http_method_names = ["get"] def get(self, request, format=None): """ Want to check from where request is coming from and allow requests coming from specific hosts only """ -
Add data based on query to API response (Django REST Framework)
I am building an API for a loan payment calculator app with Python, Django and Django REST framework. For the calculation to work, the data about loan term and loan amount that a user gives in their request needs be accessed and used together with the data from the database. I am stuck with how to accomplish this. I'd like to have a key 'payment' in JSON response, with value that equals the amount calculated. I would very much appreciate any advice on this. Here's the function that I came up with that calculates monthly payment, taking as arguments both data from database ('term_min', 'term_max', 'rate_min', 'rate_max', 'payment_min', 'payment_max') as well as query parameters (term and price), but I cannot see how to incorporate it in my view, so that my API response contains the resulting value: def calculate_payment(term_min, term_max, rate_min, rate_max, term, loan): if term == term_min: int_rate = rate_min elif term == term_max: int_rate = rate_max else: term_proportion = (term - term_min)/(term_max - term_min) int_rate = (rate_max / 100 - rate_min/100) * term_proportion term_in_months = 12 * term monthly_pmt = loan * ((1 + int_rate) ** term_in_months) / ((1 + int_rate) ** term_in_months - 1) return monthly_pmt I … -
django how to get user to display specific object
I'm learning django and I'm trying to display all items from a specific user which is the 2003-111 itemid sy sem resolve_by book 2021-2022 2 2003-111 table 2021-2022 1 2012-455 here's my models.py I'm using customuser to use email as authentication instead of username and replace my id with userid(character) class ClearanceCustomuser(models.Model): password = models.CharField(max_length=128) last_login = models.DateTimeField(blank=True, null=True) is_superuser = models.BooleanField() userid = models.CharField(primary_key=True, max_length=9) email = models.CharField(unique=True, max_length=254) is_staff = models.BooleanField() is_active = models.BooleanField() date_joined = models.DateTimeField() class Meta: managed = False db_table = 'clearance_customuser' class ClearanceItem(models.Model): itemid = models.CharField(primary_key=True, max_length=20) sem = models.CharField(max_length=1, blank=True, null=True) sy = models.CharField(max_length=9, blank=True, null=True) resolve_by = models.ForeignKey('ClearanceCustomuser', models.DO_NOTHING, db_column='resolve_by', blank=True, null=True) class Meta: managed = False db_table = 'clearance_item' for now this is my views.py def index(request): context = {} context['items'] = ClearanceItem.objects.all() return render(request, 'clearance/index.html', context) which is displaying all items. I was thinking of something like this select b.cl_itemid,b.sem,b.sy,b.resolve_by from curriculum.clearance_customuser a INNER JOIN curriculum.clearance_item b ON a.userid = b.resolve_by where resolve_by = '2003-221' -
Using Django and ccextractor to generate subtitles from video
I want to create a site which takes video, upload it to the server, process it and return subtitles generated from that video. I searched on internet and got to know about ccextractor. Though, site has something about usage with python but it's bit of a mess there. I couldn't understand just how to use it with python. I am thinking of using subprocesses along with ccextractor command line tool but unable to figure it out how to provide uploaded video to the input of the command. Solutions and Suggestions would be appreciated alot. Thanks -
Django POST method for bulk creation using postman
I have POST method in views.py in django to create an entry in database I can create a single entry using postman, but can not create bulk entries using postman can anyone help, please? models.py file from django.db import models class Users(models.Model): user = models.CharField(max_length=50,default='') function = models.CharField(max_length=50,default='') department = models.CharField(max_length=50,default='') logon = models.CharField(max_length=50,default='') def __str__(self): return self.user+" - Last_Logon: "+self.logon class Meta: ordering = ('id',) serializers.py file from rest_framework import serializers from activities.models import Users class UsersSerializer(serializers.ModelSerializer): class Meta: model = Users fields = ('id', 'user', 'function', 'department', 'logon') views.py file from django.shortcuts import render from django.http.response import JsonResponse from rest_framework.parsers import JSONParser from rest_framework import status from activities.models import Users from activities.serializers import UsersSerializer from rest_framework.decorators import api_view @api_view(['GET', 'POST']) def users_list(request): if request.method == 'GET': users = Users.objects.all() user = request.GET.get('user', None) if user is not None: users = users.filter(user__icontains=user) users_serializer = UsersSerializer(users, many=True) return JsonResponse(users_serializer.data, safe=False) # 'safe=False' for objects serialization elif request.method == 'POST': users_data = JSONParser().parse(request) users_serializer = UsersSerializer(data=users_data) if users_serializer.is_valid(): users_serializer.save() return JsonResponse(users_serializer.data, status=status.HTTP_201_CREATED) return JsonResponse(users_serializer.errors, status=status.HTTP_400_BAD_REQUEST) urls.py file from django.urls import re_path from activities import views urlpatterns = [ re_path(r'^api/activities$', views.users_list), re_path(r'^api/activities/(?P<pk>[0-9]+)$', views.users_detail), ] Thanks -
How to make a save as draft module in django
I'm working on some module but don't know to save as draft in django, Help me to solve this problem. -
Reverse for 'admin' not found. 'admin' is not a valid view function or pattern name
I'm new to Django and ,I'm trying to run a piece of code but keep getting this error: Reverse for 'admin' not found. 'admin' is not a valid view function or pattern name. The urls.py is as follows: urlpatterns = [ path('admin/', admin.site.urls), path('', include("ttgen.urls")), path('account/', include("account.urls")), ] The login.html is as follows: <div class="login-form"> <form action="{% url 'login' %}" method="post"> {{ form.as_p }} {% csrf_token %} <input type="hidden" name="next" value="{{ next }}" /> <p><input type="submit" value="LOGIN"></p> </form> <p><a href="{% url 'password_reset' %}">Forgot your password?</a></p> The views.py is as follows: if user is not None: if user.is_active: login(request, user) return HttpResponse('Authenticated '\ 'successfully') else: return HttpResponse('Disabled account') else: return HttpResponse('Invalid login') else: form = LoginForm() return render(request, 'account/login.html', {'form': form}) -
Django query ManyToMany relationship from parent=ForeignKey('self')
This is for a Django blog project. I have a model 'Profile' and 'TechStackCategory' where they have a ManyToMany relationship. Profile is the user's profile for the blog. TechStackCategory has categories of the user's stacks that they know. TechStackCategory model example: Languages, Languages -> Python, Languages -> Java, Frameworks, Frameworks -> Django class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') background_image = models.ImageField(upload_to='profile_background_pics', blank=True, null=True,) bio = models.CharField(max_length=200, help_text="200 characters or less") tech_stack_cat = models.ManyToManyField('TechStackCategory', blank=True) def __str__(self): return f"{self.user.username}'s profile" class TechStackCategory(models.Model): parent = models.ForeignKey('self', related_name='children', on_delete=models.CASCADE, blank=True, null=True) title = models.CharField(max_length=50, unique=True) def __str__(self): return f"{self.title}" class Meta: #enforcing that there can not be two categories under a parent with same slug # __str__ method elaborated later in post. use __unicode__ in place of unique_together = ('title', 'parent',) verbose_name_plural = "categories" def __str__(self): full_path = [self.title] k = self.parent while k is not None: full_path.append(k.title) k = k.parent return ' -> '.join(full_path[::-1]) So I'm following the example from this post https://dev.to/shivamrohilla/how-to-make-a-sub-and-sub-sub-categories-in-django-most-important-216p The thing is, the example in the post shows all the parents and children objects from the Category model. He filters out the query in the views as catg = Category.objects.filter(parent=None) which returns <QuerySet [<TechStackCat: … -
Using a Python ML library for DJANGO APIView: loads model on every request
I'm trying to use this python ML library and turn it into an APIView for my project. Although it works appropriately, It is taking around 20s to get the response while the huggingface link returns the same results in significantly less time. As far as I know, the hugging face runs on CPU, takes ~20s only on first load and then only 1-2s after that. I'm thinking maybe it's because this line: kp_model = KeyPhraseTransformer() is being called on every request, which is unnecessary as I just need to initiate the object once. Any way on how to improve this? services.py from keyphrasetransformer import KeyPhraseTransformer def extract_keyword(text): kp_model = KeyPhraseTransformer() keyphrases = kp_model.get_key_phrases(text) return keyphrases views.py from .services import extract_keyword class ExtractKeyphrase(APIView): def post(self, request, format=None): try: text = request.data["text"] keyphrases = extract_keyword(text) return JsonResponse(keyphrases, status=status.HTTP_200_OK, safe=False) except requests.exceptions.RequestException: Response("Request Failed", status=status.HTTP_400_BAD_REQUEST) -
Django: How to filter and display categories for author in post
Django: How to filter and display categories for author in post I guess there's something wrong with the get_queryset Category.objects.filter(post_author=username) class Post(models.Model): exercisename = models.ForeignKey('Category', on_delete=models.CASCADE) hour = models.IntegerField(default=0 ) min = models.IntegerField(default=0) file = models.FileField(null=True,blank=True,upload_to='Files') content = models.TextField() date_Posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) class Category(models.Model): name = models.CharField(max_length=100) description = models.TextField() image = models.ImageField(upload_to='images/') def userpost(request, username): context = { 'Category': Category.objects.filter(post_author=username), } return render(request, 'blog/user_Posts.html', context) -
While building Bookmyshow like project,Should I make theatre api first and then use it to book seat in another app?
while building an app like BookMyShow, do I need a pre-built particular theatre web app/DB/APIs for accessing the same through my project? https://www.geeksforgeeks.org/design-bookmyshow-a-system-design-interview-question/ Basically, I saw this system design answer, and while Building database models for this Django-rest project, One issue pops up in my mind which is, that I can not make a table for tiers as every theatre might be having different tiers, so do I need to make different app like as Theatre_name and after making DB models there, I access it from the other app called book show and book the ticket. Currently, I want to make a project which can showcase how deeply can I understand and implement difficult DB models using Django ORM, therefore, I need assistance in deciding whether Should I build a different app for theatre and use it in bookshow app for booking seats. And how complex can it get if I approach this way?