Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Django boto3 with s3 not working in production
So I am currently trying to enable large file uploads for my site www.theraplounge.co/ the only problem is I’m using boto3 to upload directly to s3 with https://justdjango.com/blog/how-to-upload-large-files as a guide. The good thing is large files get uploaded when I’m on development server. When I launch code to production server on heroku large files don’t upload anymore. I don’t think code would work locally but not in production which leads me to think the problem may be heroku 30s timeouts although I’m not sure. Anyone got a glue or a hint at what’s going on? -
Reverse for 'category-detail' with arguments '('',)' not found
I get this error when I try accessing my home page. I've tried reading similar solutions but I can't directly relate them to my case. I'm clearly missing something here but I can't see it. this is the traceback error message: Traceback (most recent call last): File "C:\Users\Muhumuza-Ivan\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\Muhumuza-Ivan\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Muhumuza-Ivan\Desktop\JobPortal\jobapp\views.py", line 68, in index return render(request, 'index.html', context) File "C:\Users\Muhumuza-Ivan\AppData\Local\Programs\Python\Python310\lib\site-packages\django\shortcuts.py", line 24, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Users\Muhumuza-Ivan\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\loader.py", line 62, in render_to_string return template.render(context, request) File "C:\Users\Muhumuza-Ivan\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\backends\django.py", line 62, in render return self.template.render(context) File "C:\Users\Muhumuza-Ivan\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\base.py", line 175, in render return self._render(context) File "C:\Users\Muhumuza-Ivan\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\base.py", line 167, in _render return self.nodelist.render(context) File "C:\Users\Muhumuza-Ivan\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\base.py", line 1000, in render return SafeString("".join([node.render_annotated(context) for node in self])) File "C:\Users\Muhumuza-Ivan\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\base.py", line 1000, in <listcomp> return SafeString("".join([node.render_annotated(context) for node in self])) File "C:\Users\Muhumuza-Ivan\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\base.py", line 958, in render_annotated return self.render(context) File "C:\Users\Muhumuza-Ivan\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\defaulttags.py", line 472, in render url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app) File "C:\Users\Muhumuza-Ivan\AppData\Local\Programs\Python\Python310\lib\site-packages\django\urls\base.py", line 88, in reverse return resolver._reverse_with_prefix(view, prefix, *args, **kwargs) File "C:\Users\Muhumuza-Ivan\AppData\Local\Programs\Python\Python310\lib\site-packages\django\urls\resolvers.py", line 802, in _reverse_with_prefix raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'category-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['jobapp/category/(?P<slug>[-a-zA-Z0-9_]+)/\\Z'] Index.html The error … -
Wagtail-2fa token doesn't work when setting up 2fa after new admin user registration
New users can't seem to set up 2fa--token always fails at set up with wagtail-2fa. Background: I set up a wagtail site a few months ago with Wagtail-2fa (which is based on django-otp). When I first set up an admin user with 2fa, the token works fine. That admin login has no problems using 2fa. When I try to set up new users, I can register the user, but when the user logs in for the first time, it requires 2fa set up (which is the desired behavior) but the token always fails. I've tried Google Authenticator, Symantec VIP, and Duo Mobile. None of them work for new users. Wagtail-2fa uses TOTP so I checked the time on the device and on the server and they appear to match at least to the minute. I've tried the same process on my localhost, staging, and production (the latter two on heroku), and none of them work (but the original admin with 2fa works). My main hypothesis now is that something broke with wagtail-2fa when I upgraded several packages: django 3.1.11 --> 4.0.5 wagtail 2.15.1 --> 3.0.1 It could be that wagtail-2fa doesn't support wagtail 3.0.1 or django 4.0.5. I'm going to … -
POST http://localhost:8000/api/project/create/ 400 (Bad Request) error when sending POST data from the React app using fetch() to Django API
I am working on a simple DRF + ReactJS app, but when I came across making a POST data from React app to the Django API, this error happens on the web console POST http://localhost:8000/api/project/create/ 400 (Bad Request) and it says the problem is on my Create.jsx This is my Create.jsx file: import React, { useState, useEffect} from 'react' import { useNavigate } from 'react-router-dom' import axios from 'axios' const Create = () => { const history = useNavigate() const [title, setTitle] = useState("") const [body, setBody] = useState("") const createProject = async () => { fetch('http://localhost:8000/api/project/create/', { method: "POST", headers: { 'Content-Type': 'application/json' }, title: JSON.stringify(title), body: JSON.stringify(body), }) console.log('title', title) console.log('BODY', body) } return ( <div className="create-project"> <p> <input type="text" onChange={e => setTitle(e.target.value)} value={title} ></input> <textarea type="text" onChange={e => setBody(e.target.value)} value={body}></textarea> <button onClick={createProject}>Submit</button> </p> </div> ) } export default Create And this is the APIView in django: views.py class CreateProject(CreateAPIView): queryset = Project.objects.all() serializer_class = ProjectSerializer urls.py if needed: path('project/create/', CreateProject.as_view(), name="create-project"),