Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
How to Refresh a OAuth2 Token by using Django OAuth Toolkit in custom Views?
What I'm doing? I have a requirement where there will be separate authorisation server and a resource server. I am using Resource owner password based grant type. I have implemented Custom Introspection View and Get Token View. (Following this and this: I have used the DOT's base class to implement my own introspection API, will add it at the end.) For both Custom Views I created, I have added it to the urls.py manually referring to it. What's happening now? Turns out, you gotta refresh token using the same /token/ url which you used to get a access token. The only difference is you gotta change the grant type to refresh_token when you wanna refresh token. It does not get processed as I have not implemented or am able to implement the refresh token. I am happy with the pre-existing internal refresh token mechanism as I don't require special/custom stuff to be in it but as I'm using a custom token view, grand_type = refresh_token is not hitting the oauthlibs refresh_token view. (My observation) urls.py from django.contrib import admin from django.urls import path, include from project.apis import ( ClientCreateTokenView, ResourceServerIntrospectView ) urlpatterns = [ path('admin/', admin.site.urls), path('o/token/', ClientCreateTokenView.as_view(), name='token_obtain_pair'), path('o/introspect/', … -
Django unittest validate method not getting called
I have below two serializers in my django app. class SubscriptionWindowPoolConfirmButtonSerializer(serializers.ModelSerializer): styles = ConfirmButtonStylesSerializer(required=False) class Meta: model = SubscriptionWindowPoolContent fields = ('value', 'styles',) def validate_value(self, value): if len(value) > 25: raise serializers.ValidationError( "Ensure button text length is not more than 25 " "characters." ) def validate(self, attrs): attrs = super().validate(attrs) if not attrs.get('styles'): attrs['styles'] = None return attrs class SubscriptionWindowPoolWithContentsSerializer(serializers.ModelSerializer, WithManualValidations): name = serializers.CharField(required=False, allow_null=True) confirm_buttons = SubscriptionWindowPoolConfirmButtonSerializer(many=True) I am trying to test the SubscriptionWindowPoolWithContentsSerializer to make sure that the value of confirm_buttons doesn't exceed 25 characters. I have added a method validate_value can be seen in first serializer. I wrote a unittest with value more than 25 characters long however no exception has been raised. Please advise what would be the best way to handle this? -
Use Multiprocessing to handle Bulk update in Django
I am writing a command that wants to update all rows from my table. Problem is, this table has millions of records. Naively I would want something like this. all_entries = MyTable.objects.all() for entry in all_entries: do_some_magic(entry) # this will do entry.save() after changes My questions is how to successfully use multiprocessing.Pool to split this into thread pools? Let's say I want to do batches of 1000 rows and keep running them in thread pools until they are done. Anyone able to help with code snippet of how this would look? -
Error showing { expected css(css-lcurlyexpected)
All things are going well but my CSS showing this error my {% block title %} {% endblock %}, {% block body%} {% endblock %} are good but don't know why {% block css%} {% endblock %} doesn't work -
How to change the format of serializers.DateTimeFileld
I use serializers.DateTimeField to return the datetime like 2022-07-24 11:49:11 from rest_framework import serializers class MixSerializer(serializers.ModelSerializer): pub_date = serializers.DateTimeField(format="%Y-%m-%d,%H:%M:%S"), ranking = serializers.IntegerField() class Meta: model = Mix fields = ('ranking','id','pub_date','detail','user') However it returns "ranking": 1, "id": 1, "pub_date": "07/24/2022 11:49P", I am not sure why it returns with P? and seconds is disappeared. Where should I fix? -
Django IN Query with different values of combination of two columns
I have to filter user from different city and state combination like Users from cities [[Mumbai,MH],[Ahmedabad,GJ],...] Where city = Mumbai and state = MH This is what i am doing now users = cls.objects.annotate(unique_city=ExpressionWrapper(Concat(F('city'),F('state'),output_field=CharField()), output_field=CharField())).filter(unique_city__in = city_list) where city_list = [MumbaiMH,AhemadabadGj,...] Is there is a better way to do this I have user model with field state and city And city model with field state and city(unique together) -
Deleting multiple rows in sqlalchemy?
I have this query but this is not all deleting the rows before insert. session.query(Device).filter(Device.user_id == user.id, Device.device_id == token_obj.device_id).delete( synchronize_session=False) -
How to convert a HttpResponse to an image in Django? just like screenshot
I want a png file and some dynamic values as response for a view, and which is working fine. Now I need to convert this httpresponse to an image to upload to the s3 bucket. Just like taking a screenshot of the HttpResponse. Is there any package ? I tried imgkit and html2image, it didnt work well. def home(request): im_io = io.BytesIO() im = Image.open(r'test.png') im.save(im_io, 'png', quality=70) im_io.seek(0) im_io_png = base64.b64encode(im_io.getvalue()) context = im_io_png.decode('UTF-8') img_tag = mark_safe(f"<img src='data:image/png;base64, {context}'/>") return render(request, 'api/home.html',{'img_tag': img_tag}) -
How to retrive data from OneToOne Relational Model in DRF using API view
I have imported User model and customized it a/c to my need and make OneToOne Relation with UserProfileModel Model. While retrieving data I got this error. "The serializer field might be named incorrectly and not match any attribute or key on the AnonymousUser instance. Original exception text was: 'AnonymousUser' object has no attribute 'gender'." My Model is : class UserProfileModel(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, related_name='userprofilemodel') gender = models.CharField(max_length=20) locality = models.CharField(max_length=70) city = models.CharField(max_length=70) address = models.TextField(max_length=300) pin = models.IntegerField() state = models.CharField(max_length=70) profile_image = models.FileField(upload_to='user_profile_image', blank=True) My Serializer looks like: class UserProfileSerializer(serializers.ModelSerializer): class Meta: model= User fields = ['id', 'name' , 'email','mobile',] class UserProfileModelSerializer(serializers.ModelSerializer): user = serializers.StringRelatedField(many=True, read_only=True) class Meta: model= UserProfileModel fields = ['user','gender' , 'locality','city','address','pin','state','profile_image', ] My view looks like: class UserProfileDataView(APIView): def get(self, request, format=None): # user = UserProfileModel.objects.all() serializer = UserProfileModelSerializer(request.user) return Response(serializer.data, status=status.HTTP_200_OK) I want to retrieve profile data of the logged user using UserProfileModel Model -
How to get a serie of request.POST values
In the following views.py: def valores(request): global peso_unitario, preco_unitario peso_unitario=[] preco_unitario=[] N=a print('N='+str(N)) for i in range(N): peso_u=request.POST['peso_u'] preco_u=request.POST['preco_u'] if peso_u.isdigit() and preco_u.isdigit(): c = int(peso_u) d = int(preco_u) peso_unitario.append(c) preco_unitario.append(d) print(a) print(preco_unitario) if i<N-1: return render(request, 'valores.html') else: return render(request, 'pacote.html', {'peso_unitario': peso_unitario, 'preco_unitario': preco_unitario}) else: res = 'Apenas numero.' return render(request, 'pacote.html', {'res': res}) I have a function that receives a global value N=a, this value was received from the user, now I need to receive N times the both values in request.POST loop, but each time the user needs to enter the values. I don't know how to do this. -
How can I get the number of currently running coroutines of gevent>\?
We are currently developing in the mode of gunicorn+django+gevent. I would like to ask if there is any command line method to obtain the number of currently running coroutines when the service is running -
CORS error when adding <script> tag as a URL query parameter
What I'm working on are making Vue frontend to send GET request with filters to backend Django server. The issue that I'm currently encounter is if is I pass in <script> into the as a value for the filter, it will returns CORS error. For example: url?name=<script> CORS error However, other tag such as <body> works fine as I encoded the value before send to the server. Is there anyone have such experience and what are the possible issues to this? Thanks.