Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Django, passing get query has a value to filter query, calls get query twice
I have get query which is passed as a value in filter query ,when running the code get query is called twice. #get query employee = Employee.objects.get( user=self.request.user.email, project=self.request.org_id) #filter query LeaveApproval.objects.filter(approver=employee) #dbCallLog SELECT ••• FROM "leavetracker_employee" WHERE ("leavetracker_employee"."project_id" = 'f5b10d49-9056-4faa-b95a-251f998a724f'::uuid AND "leavetracker_employee"."user_id" ='rajini@gmail.com') LIMIT 21 2 similar queries. Duplicated 2 times. Why employee call is duplicated twice? Thanks in advance. -
Tailwind Dynamic Colour Based on Page/URL
I was hoping someone new how I could dynamically set text/bg colours based on the current page I'm on? I've brought in a navbar from flowbite and it looks like it designed to highlight a specific option based on the page you're on but I don't quite understand how to make that happen. I'm using the Tailwind CDN and Flowbite CDNs. Thanks, Mitchell -
Django views.py code running automatically whenever I reload the server
I have logs which are uploaded and inserted into MySQL table from CSV files using upload_log endpoint in views.py of a Django app. I also have another views.py in a different sub-app (Django as well) that parses the existing data from the logs table and splits it in different rows according to conditions. The problem is the parsing happens whenever I reload the server which creates duplicates besides the fact that it is not my intention to have it like this. I need to have it so that whenever data is uploaded (post is triggered), it runs the function on that uploaded data to parse the logs. Edit (clarification): It doesn't execute when I do py manage.py runserver - But it executes after I run the runserver command and CTRL + S inside the file to reload the server. I would appreciate it if someone guides me through this. Here's the views.py of that task (Logs app): from rest_framework import viewsets from rest_framework.decorators import action from api.packets.models import Fields from .models import LogsParsed from api.logs.models import Logs from .serializers import LogsParsedSerializer class getLogs(viewsets.ModelViewSet): serializer_class = LogsParsedSerializer queryset = LogsParsed.objects.all() parsedLogs=[] for log in Logs.objects.all(): fields = Fields.objects.filter(pac_id=log.message_id_decimal) binaryTest=log.data_binary for field … -
How do I send django object list to javascript?
I want to django query to javascript.so I changed queries to list. I sended list to javascript.But list were not displayed by console log. class Comment_List_TV(ListView): template_name = 'account/user_comment_list_tv.html' def get_queryset(self): Comment_list_query = list(Comment_tv.objects.none()) if self.request.user.is_authenticated: Comment_list_query = list(Comment_tv.objects.filter(user=self.request.user)) print(Comment_list_query) return Comment_list_query Print display object list. But const mydata = "{{Comment_list_query}}"; console.log(mydata); Console log does not display django's object list. why? How do I send django object list to javascript? -
How to call a function in django channels consumers
I defined a sync_to_async def in consumers and i am trying to call it after the receice async function. but no clue how to do this this is my code : async def receive(self, text_data): text_data_json = json.loads(text_data) wsRecDeck = text_data_json['wsDeck'] await self.channel_layer.group_send( self.game_room_name, { 'type': 'send_deck_to_all', 'wsRecDeck': wsRecDeck, } ) @database_sync_to_async def updateDeck(self, wsRecDeck): if(LiveDeckDB.objects.filter(current_deck = wsRecDeck).exists()): LiveDeckDB.objects.filter(current_deck = wsRecDeck).delete() dbDeck = LiveDeckDB.objects.create(current_deck = wsRecDeck) dbDeck.current_deck = wsRecDeck dbDeck.save() print('|||||||Print Test For DB: ',dbDeck.current_deck) async def send_deck_to_all(self, event): wsRecDeck = event['wsRecDeck'] await self.send(text_data=json.dumps({ 'wsAllDeck': wsRecDeck, })) I am trying to call the updatedeck function immediatly after the receive function but i have no clue. Any tips? -
Django Channels sending multiple messages to same channel
Referring to documentation here I'm sending messages to the single fetched channel_name I'm able to successfully send messages to the specific channel Issues I'm facing On the channels it's sending messages multiple times For Example - When I send first message, I receive 1 time. On second message, I'm getting same messages twice. On third message, I'm geting same message 3 times. and so on... class ChatConsumer(AsyncJsonWebsocketConsumer): async def connect(self): self.user_id = self.scope['url_route']['kwargs']['user_id'] await self.save_user_channel() await self.accept() async def disconnect(self, close_code): await self.disconnect() async def receive_json(self, text_data=None, byte_data=None): message = text_data['message'] to_user = text_data['to_user'] to_user_channel, to_user_id = await self.get_user_channel(to_user) channel_layer = get_channel_layer() await channel_layer.send( str(to_user_channel), { 'type': 'send.message', 'from_user': self.user_id, 'to_user': str(to_user_id), 'message': message, } ) await channel_layer.send( str(self.channel_name), { 'type': 'send.message', 'from_user': self.user_id, 'to_user': str(to_user_id), 'message': message, } ) async def send_message(self, event): from_user = event['from_user'] to_user = event['to_user'] message = event['message'] await self.send(text_data=json.dumps({ 'from_user': from_user, 'to_user': to_user, 'message': message, })) @database_sync_to_async def get_user_channel(self, to_user): try: self.send_user_channel = ChatParticipantsChannel.objects.filter( user=to_user).latest('id') channel_name = self.send_user_channel user_id = self.send_user_channel.user.user_uid except Exception as e: self.send_user_channel = None channel_name = None return channel_name, user_id @database_sync_to_async def save_user_channel(self): self.user = User.objects.get(user_uid=self.user_id) ChatParticipantsChannel.objects.create( user=self.user, channel=self.channel_name ) @database_sync_to_async def delete_user_channel(self): ChatParticipantsChannel.objects.filter(user=self.user).delete() -
Django - Reverse for 'topic' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<topic>[^/]+)/\\Z']
I'm learning Django and there was a problem. I will be grateful if you help Reverse for 'topic' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P[^/]+)/\Z'] views: def topic(request, topic): topic = New_topic.objects.get(id=topic) comments = topic.comment_set.order_by('+date') context = {'topic':topic, 'comments':comments} return render(request, 'topic.html', context) urls: from django.urls import path from . import views app_name = "forum" urlpatterns = [ path('', views.main, name='main'), path('<int:topic>/', views.topic, name='topic') ] models: from django.db import models from django.contrib.auth.models import User class New_topic(models.Model): text = models.CharField(max_length=64) date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.text class Comments(models.Model): topic = models.ForeignKey(New_topic, on_delete=models.CASCADE) text = models.TextField() date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.text template: main.html {% block content %} {% for list_forum in list %} <a href="{% url 'forum:topic' topic.id %}">{{ list_forum }}</a> {% endfor %} {% endblock content %} topic.html {% block content %} {{ topic }} {% for comment in comments %} {{ comment.text|linebreaks }} {% endfor %} {% endblock content %} -
Python: Display either Video or Image File, but it shows both
I have been working on a social media website where you can upload images and videos and follow other users. I managed to upload and display uploaded files to the website. I used FileField to load the image and video files, but when I implement it in my Template it shows both spaces, because there both using the same source url {{ source.file.url }} models.py class Post(models.Model): title = models.CharField(max_length=150) file = models.FileField(upload_to='uploads/%Y-%m-%d') models code works perfectly feeds.html {% if post.file.url %} <video class="video-context" width="500px" height="500px" controls> <source src="{{ post.file.url }}" type="video/mp4"> </video> {% endif %} {% if post.file.url %} <img class="image-context" src="{{ post.file.url }}" type="image/jpg" type="image/jpeg"> {% endif %} heres a sreenshot empty video player over img Now the problem is that both File Types are going trough one Model: FileField. The source is {{ source.file.url }} , the HTML is searching both files, but there only either image or video, so what can i do with the other empty file? How can I hide it? -
I created a comment section in my Django project and i want to redirect users to that same post they just commented on after they posted the comment
right now it redirects them to the home page. here is the views.py file: class AddReviewView(CreateView): model = Review form_class = ReviewForm template_name = 'blog/add_review.html' def form_valid(self, form): form.instance.post_id = self.kwargs['pk'] return super().form_valid(form) success_url = reverse_lazy('blog-home') and here is the models.py file: class Post(models.Model): title = models.CharField(max_length=100) price = models.DecimalField(default=0, max_digits=9, decimal_places=2) post_image = models.ImageField(null=True, blank=True, upload_to='post_images/') content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) class Review(models.Model): post = models.ForeignKey(Post, related_name="reviews", on_delete=models.CASCADE) name = models.CharField(max_length=255) body = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s' % (self.post.title, self.name) here are my url patterns: urlpatterns = [ path('', PostListView.as_view(), name='blog-home'), path('marketplace/', MarketplaceView.as_view(), name='blog-marketplace'), path('freelancers/', FreelancersView.as_view(), name='blog-freelancers'), path('user/<str:username>', UserPostListView.as_view(), name='user-posts'), path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'), path('post/new/', PostCreateView.as_view(), name='post-create'), path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'), path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'), path('about/', views.about, name='blog-about'), path('search-posts/', views.search_posts, name='search_posts'), path('post/<int:pk>/Review/', AddReviewView.as_view(), name='add_review'), ] pleae help me!! note: i want to change the success_url = reverse_lazy('blog-home') to redirect the the page they just commented on