Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Sending data from C# script (in unity) to django web server
What I want: I have a Django web server with PostgreSQL database on Heroku, I want to store and display some data (like High Scores and similar) from my unity game. What I managed to do: I managed to create get and post requests in C# and get responds from them. My problem: The post requests only work if I have CSRF(I have some knowledge how it works and my assumption is that I should keep it on) turned off in my Django web server. My question: Can I, and how (preferably in a simple and easy way) send some simple data (strings) to my Django web server hosted on Heroku from a C# script run in my Unity game while having CSRF on (or if I don't need it to be on/use some other kind of protection). -
percentage of file uplaoded in django
I want to know how much percent of file is uploaded in djnago. This is my html. <form action="/contribute/" method="POST" enctype="multipart/form-data"> {% csrf_token %} <ul class="cform"> <li class="img_uplabel">Image:</li> <li class="img_up">{{ form.image }}</li> <button type="submit" class="up_btn">Go</button> </ul> </form> this is my models.py class Photo(models.Model): image = models.ImageField(upload_to="home/images", validators=(image_validator)) -
How do I authenticate/protect non api_views with DRF + JWT eg. rendering a private page
I understand how to protect this for example, get the token, store it as cookie, then get the access token via the cookie and send it via Ajax to /api/hello and I get my JSON @api_view() @permission_classes([IsAuthenticated]) def hello(request): return Response({'message': 'hello this is protected'}) But how would I protect this page where I want only people who are authenticated to see the page, eg. if they click this URL /secretmessage def secret_message(request): return render(request, 'secret_message.html') -
display variable with floatformat based on condition
i want to limit digits in numbers bigger than 1 by 2 digits. i want to find out if there is a short-syntax to simplify code from 5 lines to a one liner and learn from your experience. expected output : 100 10 1 0.00001 working code {% if number > 1 %} {{ number | floatformat:2 }} {% else %} {{ number }} {% endif %} im looking for a possible syntax like this pseudo code {{ number | if number > 1 floatformat:2 }} -
Django Integrity exception
Any of my exception is working. I couldn't figure out where I make mistake. Whatever is the exception, the else block is always executed. Any ideas please? def upload_road_type(request, pk): template = "networks/roadtype.html" roadnetwork = RoadNetwork.objects.get(id=pk) roadtypes = RoadType.objects.filter(network_id=pk) list_roadtype_instance = [] if request.method == 'POST': form = RoadTypeFileForm(request.POST, request.FILES) if form.is_valid(): datafile = request.FILES['my_file'] datafile = datafile.read().decode('utf-8').splitlines() datafile = csv.DictReader(datafile, delimiter=',', quoting=csv.QUOTE_NONE) for row in datafile: row = {k: None if not v else v for k, v in row.items()} try: road_type_id = row['id'] name = row['name'] except IntegrityError: messages.error(request, "id must be integer") return redirect('network_details', roadnetwork.pk) else: roadtype = RoadType( road_type_id=road_type_id, name=name, network=roadnetwork) list_roadtype_instance.append(roadtype) RoadType.objects.bulk_create(list_roadtype_instance) return redirect('network_details', roadnetwork.pk) else: form = RoadTypeFileForm() return render(request, template, {'form': form}) -
Django - Simple password reset using FormView, sending random string as password in email, without using tokens
How can I send random string as new password in email to reset password. I am having difficulty starting to write the code all other examples are using built-in views but I want to use form view. -
Django rest framework api - permission error - Access denied for this endpoint
I am using the following in my project: Django 3.2.3 djangorestframework 3.12.4 This is my first django project using DRF for an api to my project. I want only people with the correct credentials (membership of a particular Django group) to be able to use the api. I have created one such user, for manual testing. I am able to login to obtain a token from the Here are my files api/permissions.py class MyBasePermission(permissions.BasePermission): def has_permission(self, request, view): # TODO: Some common permissioning task return True class FooPermission(MyBasePermission): """Custom Permission Class for Foo Model """ def has_permission(self, request, view): if not super().has_permission(request, view): return False if request.user and (request.user.is_superuser or request.user.is_staff): return True if request.user and request.user.groups.filter(name="FooGroup"): return True return False api/views.py class FooViewSet(viewsets.ModelViewSet): """Endpoint for Foo Model""" authentication_classes = [authentication.TokenAuthentication] permission_classes = [IsAuthenticated, FooPermission] queryset = Foo.objects.all() serializer_class = FooSerializer def create(self, request, *args, **kwargs): pass def destroy(self, request, *args, **kwargs): pass def perform_create(self, serializer): pass api/urls.py router = routers.SimpleRouter() router.register( 'foo', FooViewSet, basename='foo-crud' ) urlpatterns = [ path('login/', UserLoginApiView.as_view(), name='login'), url('', include(router.urls)) ] myproject URLsConf urlpatterns = [ path('', TemplateView.as_view(template_name="homepage.html"), name='homepage'), path('api/v1/', include('api.urls') ), # ... ] httpie login http POST http://127.0.0.1:8000/api/v1/login/ username="user1" password="password1" HTTP/1.1 200 OK Allow: … -
Django is not rendering ListView
I had another post related to this but my code was complex so the communication was difficult. I completely stripped off the issue from the unnecessary details and came up with a very minimal example shown below: templates/base.html: <html> <body> <p>I am base.html</p> {% block content %} {% endblock content %} </body> </html> templates/blog.html: {% extends 'base.html' %} {% block content %} <p>I am blog.html</p> {{ blog_list }} {% for blog in blog_list %} {{ blog.title }} {% endfor %} {% endblock %} And blog/views.py from django.views import generic from .models import Blog class BlogList(generic.ListView): queryset = Blog.objects.filter() template_name = 'blog.html' # context_object_name = 'blog_list' class BlogDetail(generic.DetailView): model = Blog template_name = 'blog.html' That outputs this: [![enter image description here][1]][1] I was expecting the list of blog titles to be rendered there. I debugged the BlogList class and queryset value was this: <QuerySet [<Blog: First Page>, <Blog: Intro>]> So, the query is not empty. I have been completely frustrated by this issue. Anyone know what's going on? [1]: https://i.stack.imgur.com/qWAwR.png -
Django channels consumer
For django channels I have consumer file like this: from channels.generic.websocket import WebsocketConsumer from asgiref.sync import async_to_sync import json class chatConsumer(WebsocketConsumer): def connect(self): async_to_sync(self.channel_layer.group_add)( 'my_socket', self.channel_name ) self.accept() def receive(self, text_data): async_to_sync(self.channel_layer.group_send)( 'my_socket', { 'type': 'chat_message', 'data': text_data } ) def chat_message(self, event): json_data = json.loads(event['data']) # get received data as json respons_test = json.dumps(json_data) # make response text print("chat_message") # Sometimes this is printed few times self.send(text_data=respons_test) It seems chat_message method is running few times sometimes. I'm not sure how this exactly works but when I print into chat_message, it is printed sometimes once, sometimes more than once. (I don't change clients/browsers count, and also in front-end, receiver gets message correctly, only one time). Question: its normal few times running of chat_message? or I have something wrong in code? -
How to compress base64 decoded video data using ffmpeg in django
I want to upload the video/audio file in my django-channels project. So I uploaded video(base64 encoded url) from websocket connection. It is working fine. But now after decoding base64 video data I want to compress that video using ffmpeg.But it showing error like this. ''Raw: No such file or directory'' I used 'AsyncJsonWebsocketConsumer' in consumers.py file.Here is my code: consumers.py: async def send_file_to_room(self, room_id, dataUrl, filename): # decoding base64 data format, datastr = dataUrl.split(';base64,') ext = format.split('/')[-1] file = ContentFile(base64.b64decode(datastr), name=filename) print(f'file: {file}') # It prints 'Raw content' output_file_name = filename + '_temp.' + ext ff = f'ffmpeg -i {file} -vf "scale=iw/5:ih/5" {output_file_name}' subprocess.run(ff,shell=True) May be here ffmpeg can not recognize the file to be compressed. I also tried to solve this using post_save signal. signals.py: @receiver(post_save, sender=ChatRoomMessage) def compress_video_or_audio(sender, instance, created, **kwargs): print("Inside signal") if created: if instance.id is None: print("Instance is not present") else: video_full_path = f'{instance.document.path}' print(video_full_path) // E:\..\..\..\Personal Chat Room\media\PersonalChatRoom\file\VID_20181219_134306_w5ow8F7.mp4 output_file_name = filename + '_temp.' + extension ff = f'ffmpeg -i {filename} -vf "scale=iw/5:ih/5" {output_file_name}' subprocess.run(ff,shell=True) instance.document = output_file_name instance.save() It is also causing "E:..\Django\New_Projects\Personal: No such file or directory". How can I solve this issue? Any suggetions.It will be more helpful if it can be … -
Need help implementing comments in Django
More specifically, you need to rewrite the working function to the DetailView class, or offer a better implementation. And it would be great to get a solution for binding a User to a comment, since in my case I have to choose from all the existing ones. Thanks in advance! Function: def product_detail(request, pk): template_name = 'main/product_detail.html' product = get_object_or_404(Product, pk=pk) comments = product.comments.filter(active=True) new_comment = None # Comment posted if request.method == 'POST': form = CommentForm(data=request.POST) if form.is_valid(): # Create Comment object but don't save to database yet new_comment = form.save(commit=False) # Assign the current post to the comment new_comment.product = product # Save the comment to the database new_comment.save() else: form = CommentForm() return render(request, template_name, {'product': product, 'comments': comments, 'new_comment': new_comment, 'form': form}) Model: class Comment(models.Model): product = models.ForeignKey(Product,on_delete=models.CASCADE,related_name='comments') username = models.ForeignKey(Profile, on_delete=models.CASCADE) body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=False) class Meta: ordering = ['created_on'] def __str__(self): return 'Comment {} by {}'.format(self.body, self.username) Form: class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('username', 'body') Template: <!-- comments --> <h2>{{ comments.count }} comments</h2> <hr> {% for comment in comments %} <p>{{ comment.body | linebreaks }}</p> <small class="text-muted">Posted by <b>{{ comment.username }}</b> on {{ comment.created_on }}</small><br><br> … -
How to create and serialize an unmanaged model Django
I'm trying to create an unmanaged model and its associated serializer but I'm having great difficulty. My first problem is that I can't find any tutorials online on how to create an unmanaged model. I'm just looking for a very simple example on how to do this. I understand as part of the docs that you need to specify managed = False but that's just a start. So far, I've literally only found one link (that isn't very helpful): https://riptutorial.com/django/example/4020/a-basic-unmanaged-table- Right now, I've tried to combine what I've seen but I'm getting an error (probably because I don't really understand how the overall architecture is meant to work). In my situation, I currently have tables in my database to which I want to create a model that retrieves certain data from the different tables in one endpoint. For arguments sake, let's say that I've got one piece of data from one table. This is what I've got so far: UserModel from django.db import models class UserDetails(models.model): user = models.CharField(db_column="LABEL", max_length=255) class Meta: managed = False UserSerializer from rest_framework import serializers from models.user import UserModel class UserSerializer(serializer.ModelSerializer): class Meta: model = UserModel fields = "__all__" UserViewSet from rest_framewirk.viewsets import ModelViewSet from … -
How to encrypt email field in django AUTH_USER_MODEL
We are using django default user model. For security purposes, customer requested to encrypt the "email field" inside database. I am not looking for procedure of encrypting one model field, I am just looking for how can I get hold of default user model email field and encrypt it. Please note our project is in development phase, so, we can run migration from freshly. What and how is the best way to achieve it? Thanks in advance. -
django multiple database with multiple server
I have a server deploying with single database. I want to run another server(for crawling) with multiple database(existing one, new one). I will save raw data from crawling in new one(DB). After data processing, save them in existing one. So, deploying server can use them. How can I do that? -
Linking Django Path to another localhost
I am running a Django project on localhost:9001 port and I want to add path like /graphql to open localhost:8080 actually Hasura graphql is running on that url. This is the code for app_name/urls.py urlpatterns = [ path('', include('core.urls')), path('admin/', admin.site.urls), path('graphql/',include('core.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) While this is the code for app_name/core/urls.py urlpatterns = [ path('user/<slug:event>', views.UserEventView.as_view()), path('',views.upload_file,name='home'), path('graphql/', GraphQLView.as_view(graphiql=True, schema=schema)), ] I want to change graphql/ path to Hasura graphql running on localhost:8080. Can Anyone please help? -
Django - Not able to access the data from model
I am currently using django 3.2 and when I try to print the models data in the views it throws the following error My views look like this from django.shortcuts import render, HttpResponse, redirect from django.contrib.auth.decorators import login_required from user.models import Student @login_required def home(request): user = request.user student_user = Student.objects.all() student_users = [] for user in student_user: student_users.append(user.User.username) stu_user = request.user.username student_list_set = set(student_users) if stu_user in student_list_set: data = Student.objects.filter(User=request.user) print(data.Name) params = { 'data':student, } return render(request, 'dashboard/student/dashboard.html', params) When I try to print the print the data.name. It throws the following error AttributeError at / 'QuerySet' object has no attribute 'Name' My models.py file looks like this class Student(models.Model): User = models.ForeignKey(User, on_delete=models.CASCADE) Name = models.CharField(max_length=50) Profile = models.ImageField(upload_to = upload_student_profile_to, default = 'defaults/student_profile.png') class_choices = (('1','1'), ('2','2'), ('3','3'), ('4','4'),('5','5'),('6','6'),('7','7'),('8','8'), ('9','9'),('10','10')) Class = models.CharField(max_length=100, choices=class_choices) section_choices = (('A','A'),('B','B'),('C','C'),('D','D'),('E','E')) Section = models.CharField(max_length=100, choices=section_choices) Roll = models.IntegerField(blank=True) Number = models.IntegerField(blank=True) is_banned = models.BooleanField(default=False) def __str__(self): return self.Name + " of " + self.Class -
Sum list of datetime.time
I have a list of datetime.time [ datetime.time(2, 0), datetime.time(1, 0), datetime.time(1, 0), ...] How can I do the sum of those values ? I tried to simply to sum(mylist) but I have an error "unsupported operand type(s) for +: 'int' and 'datetime.time'" -
How to query a Django JSONField with a nested dictionary?
I'm using Django 3.2.3 / Python 3.7.8 / PostgreSQL 12.3 models.py class Booking(models.Model): reference = models.CharField(max_length=15, unique=True) services = models.JSONField() The services structure is: { '1':{ 'id': 3, 'name': 'Name 1' }, '2':{ 'id': 4, 'name': 'Name 2 }, '3':{ 'id': 3, 'name': 'Name 3 }, ... } How to filter the Booking with services having id 3? I tried Booking.objects.filter(services__contains=[{'id': 3}]) but couldn't get through. Kindly help. -
Remove allauth from Django project created by cookiecutter
I am at a beginning of a "company web app project". I tried a Django cookiecutter template, and so far I like what I see. What I see I won't need is the user registration, password reset, social-app logins, and so on, because I will use LDAP for my user login. Afaik the stuff I don't need is provided by that "allauth" apps (please correct me). What would be the steps needed to remove this functionality so I can have the authentication more like when starting a project via Django "starproject"? I don't have any crucial data in the DB, or any models I care about, so instructions for a fresh start would be ideal. MY idea was to remove the allauth apps from "APPS" in settings and only then do the initial migrations, but something tells me it won't be that easy. I am an intermediate python dev, but new to Django. Thank you all in advance for your ideas. -
When i redirect to signup to login page my response success message is not displaying in django using ajax submit form?
I am using Django Rest framework, Please help why my success message is not showing on signin or login page when i redirect to signup to signin page. Please check my script carefully. MY views.py file This file contains my json response in the form of success and error messages: @api_view(['GET', 'POST']) @csrf_exempt def signup(request): if request.method == 'POST': serializer = UserSerializer(data=request.data) serializer1 = ProfileSerializer(data=request.data) if serializer.is_valid() and serializer1.is_valid(): # serializer.is_valid(raise_exception=True) # serializer1.is_valid(raise_exception=True) user = serializer.save() gender = serializer1.data['gender'] birth_date = serializer1.data['birth_date'] profile = Profile(user=user, gender=gender, birth_date=birth_date) profile.save() data = {'result': 'success', 'message': 'You have registered successfully and now you can login'} return Response(data=data, status=201) elif not serializer.is_valid(): serializererrors = serializer.errors data = { 'result': 'error', 'message':serializererrors} return Response(data=data) elif not serializer1.is_valid(): serializer1errors = serializer1.errors data = { 'result': 'error', 'message': serializer1errors} return Response(data=data) if not request.user.id and request.method == 'GET': serializer = UserSerializer() serializer1 = ProfileSerializer() return render(request, 'register.html', {'serializer':serializer, 'serializer1':serializer1}) My register.html file it includes my html code: Please help why my success message is not showing on signin or login page when i redirect to signup to signin page. Please check my script carefully. {% extends 'layout.html' %} {% block body %} <!DOCTYPE html> <html> <head> <meta … -
How to convert base64 variable to plain number in django template?
Let's say, we have the following place in the django template: <a href="{% settings_value "BASE_URL" %}{% url 'password_reset_confirm' uidb64=uid token=token %}{% if link_query_params %}?{{ link_query_params }}{% endif %}" target="_blank"> How to convert uid to the plain number? -
Create django question object with 4 not same choices
I want to create a question object in django without choices repeated. Like: 1) 2 2) 5 3) 5 4) 7 2 and 3 have same value and should throw error or response(I'm using rest framework) # models.py class Question(models.Model): field = models.ForeignKey('Field', on_delete=models.CASCADE) writer = models.ForeignKey(User, on_delete=models.CASCADE) question = models.TextField(unique=True) choice1 = models.CharField(max_length=200) choice2 = models.CharField(max_length=200) choice3 = models.CharField(max_length=200) choice4 = models.CharField(max_length=200) created = models.DateTimeField(auto_now_add=True) approved = models.BooleanField(default=False) ignored = models.BooleanField(default=False) any solution for this problem? -
Django Logging - Unable to set propagate to False
What I'm experiencing is getting duplicate entries in my logs. I've looked around, and it seems that I have to set 'propagate': False in my loggers configuration which I have already done. However when I printout the logger.propagate it returns True. I even tried to manually set logger.propagate = False but it still returns True and I'm receiving duplicate entries in my logs. What might be the cause of problem? import logger logger = logging.getLogger(__name__) logger.propagate = False # Getting both twice logger.error('Something went wrong!') logger.error(logger.propagate) # Returns True LOGGING = { "version": 1, "disable_existing_loggers": False, "formatters": { "simple": { "format": "{levelname} {message}", "style": "{", } }, "handlers": { "console": { "level": "DEBUG", "class": "logging.StreamHandler", "formatter": "simple", }, }, "loggers": { "app": { "level": "DEBUG", "handlers": ["console"], 'propagate': False, } }, } -
How to save history data to different database in Django?
I am using django-tenants for creating multitenant app and have successfully done it. But now I want to save history data of tenants to a different database. How to accomplish this. Please help -
python : How can I do not encode / to %/F
def redirect_login_page(request): callback_url = BASE_DIR + CALLBACK_URI return redirect( f"https://kauth.kakao.com/oauth/authorize?client_id={KAKAO_REST_API_KEY}&redirect_uri={callback_url}&response_type=code") when i use kakao-api's social login, The redirect_uri is automatically encoded :, / to %3A, %2F. So, I can't redirect the page. Is there any solution for stopping autoencoding the url character?