Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
coverage won't test the whole files test coverage right?
I'm trying to understand if we we have lot of services file written in the Djano project. We're writing the tests using pytest framework. I have a question related to this command coverage run -m pytest && coverage report && coverage xml So the coverage will not show all the files which has not test cases it will just show the file you have written the test for and how much you have written(in percentage)? is my understanding correct? Can we see somehow for all the files it hasn't covered yet. I tried running the command but its only showing me for one file can someone explain me here -
The rewind slider does not work on the video when trying to replay via Html5 Django
I tried to do video hosting on Django and play videos using Html5, but the video cannot be rewound, the problem disappears after the page is reloaded post.html {% extends 'main/base.html' %} {% block content %} <link href="https://vjs.zencdn.net/7.14.3/video-js.css" rel="stylesheet" /> <script src="https://vjs.zencdn.net/7.14.3/video.min.js"></script> <div class="container"> {% for p in post %} <h1>{{p.title}}</h1> <div> <video id='my-video-{{p.id}}' class='video-js' controls preload='none' width='640' height='264'> {% if door == "1" %} <source src="{{ p.video_door_1.url }}" type="video/mp4"> {% else %} <source src="{{p.video_door_2.url }}" type="video/webm"> {% endif %} <p class='vjs-no-js'> Чтобы посмотреть это видео, пожалуйста, включите поддержку JavaScript и обновите свой браузер. </p> </video> <div> <button onclick="changeSpeed('my-video-{{p.id}}', 0.5)">0.5x</button> <button onclick="changeSpeed('my-video-{{p.id}}', 1)">1x</button> <button onclick="changeSpeed('my-video-{{p.id}}', 1.5)">1.5x</button> <button onclick="changeSpeed('my-video-{{p.id}}', 2)">2x</button> <button onclick="changeSpeed('my-video-{{p.id}}', 5)">5x</button> </div> </div> <script> // Инициализация плеера Video.js для каждого видео var player = videojs('my-video-{{p.id}}', { // Настройки плеера }); function changeSpeed(playerId, speed) { // Получение объекта плеера по его идентификатору var targetPlayer = videojs(playerId); // Определение и установка новой скорости воспроизведения targetPlayer.playbackRate(speed); } </script> {% endfor %} </div> {% endblock %} views.py def show_post(request, post_slug, door): post = Avtobus.objects.filter(slug=post_slug) context = { 'post': post, 'menu': menu, 'door': door, 'title': 'Видео', } return render(request, 'main/post.html', context=context) -
what is React py and in how much time it will be stable?
React.py is a Python library that enables developers to build web applications using the principles and concepts of React, a popular JavaScript library for building user interfaces. React.py allows developers who are more comfortable with Python to leverage the benefits of React without having to write JavaScript code. At the time of my knowledge cutoff in September 2021, React.py was not a widely recognized or established library in the Python ecosystem. It is important to note that the development of open-source libraries and frameworks can be unpredictable, and it is difficult to determine an exact timeline for when a particular library will reach a stable version. However, typically, the stability of a library depends on factors such as community adoption, active maintenance, and the resolution of any reported issues or bugs. Therefore, it is advisable to check the latest updates and releases from the React.py community to assess the current status and stability of the library. Regarding the differences between React.py and React.js, the key distinction lies in the programming language used. React.js is primarily used with JavaScript, while React.py enables the use of Python for building web applications with React concepts. While React.js has a large and established ecosystem, … -
How to make given url path restful
/account/admin/otp /account/admin/otp/verification /account/delegate/otp /account/delegate/otp/verification /account/refresh-token /account/register-delegate /account/delegate-types /account/delegate-proof-documents In here account is the app name in Django and the there is User model and I try to provide the separate endpoint for the delegate and admin login -
code for understand that facebook has removed a link
how to check automatical that a facebook link has been removed I want to write a python script that will take input of a list of facebook links and automatically check whether these links have been removed or not. Finally it will give me another list that contains the result -
Need console bar that should display messages of my views.py
I am using django to build my application. here is my code: def upload_sequence(request): if request.method == "POST": sequence = request.POST.get("sequence") #sequence = sequence.replace("\n", "") file = request.FILES.get("file") try: if sequence: script_dir = os.path.dirname(os.path.abspath(__file__)) file_path = os.path.join(script_dir, "sequences.fasta") with open(file_path, "w") as f: f.write(sequence) elif file: script_dir = os.path.dirname(os.path.abspath(__file__)) file_path = os.path.join(script_dir, "sequences.fasta") with open(file_path, "wb") as f: for chunk in file.chunks(): f.write(chunk) calculate_features(file_path) except Exception as e: print(f"Error analyzing sequence: {e}") return JsonResponse({"status": "Error analyzing sequence"}, status=500) return redirect("results") return render(request, "upload.html") In this code: calculate_features(file_path) is a function which is displaying messages as: completed_steps += 1 progress=int((completed_steps / total_steps) * 100) progress_callback(f"Sequence {ID} uploaded successfully", progress) I tried man methods to display these messages in html webpage in real time when the analysis runs, but none works. Please suggest me a good method for this. -
How can I fix 'You can't execute queries until the end of the 'atomic' block' error in Django signals?
I'm using Django 4.1.3 in my signals.py, for an object, I want to do these things: Create an object of CLASS1 Create an objects of CLASS2 Call a function for sending a message and this is my code: @receiver(pre_save, sender=Event) def is_confirmed_changed(sender, instance, **kwargs): if instance.id is None: pass else: e = Event.objects.get(id=instance.id) try: with transaction.atomic(): CLASS1.objects.create( user=instance.creator, ) except: pass send_text_message() try: with transaction.atomic(): CLASS2.objects.create( event=e, ) except: pass on my localhost everything looks fine but when I test it on my server i get this error: You can't execute queries until the end of the 'atomic' block. I tried adding "with transaction.atomic()" or changing the order of my steps but i failed anyway. -
Django: Complex slot booking
I am working on a project where clinic will be able to book a slot I have done the slot booking code but now I want that when user select the date for another user he should not be able to view the already booked slots I have tried the following code Please review the same and let me know what i have done wrong Please help me if urgent view.py def treatment_plan(request, pk): title = 'Plan Treatment' patient_unique_number = request.GET.get("punique_number") treatment_session = request.GET.get("treatment_session") email = request.GET.get("email") pname = request.GET.get("name") address = request.GET.get("address") phone = request.GET.get("phone") treatment_name = request.GET.get("treatment_name") treatment_category = request.GET.get("treatment_category") treatment_code = request.GET.get("treatment_code") treatment_duration = int(treatment_session) time_slots = [] booked_slots = [] if request.method == "POST": session_dates = request.POST.getlist("session_dates[]") session_times = request.POST.getlist("session_times[]") if not session_dates: messages.error(request, 'Please select the date') if not session_times: messages.error(request, 'Please select time') for i in range(0, len(session_dates)): # Convert the date format from "DD/MM/YYYY" to "YYYY-MM-DD" session_date = datetime.strptime(session_dates[i], "%d/%m/%Y").strftime("%Y-%m-%d") appointment = Appointment.objects.create( patient_unique_number=patient_unique_number, date=session_date, time=session_times[i], patient_email=email, patient_name=pname, patient_treatment=treatment_name, patient_treatment_code=treatment_code, patient_treatment_category=treatment_category, patient_address=address, phone=phone ) appointment.save() messages.success(request, "Slots booked successfully") # Generate time slots from 9 AM to 9 PM with 30-minute intervals start_time = datetime.strptime("09:00", "%H:%M") end_time = datetime.strptime("21:00", "%H:%M") current_time = start_time … -
Managing User Authentication Across Multiple Django Projects with a Custom User Model
I have three Django projects: Project A, Project B, and Project C. Project A serves as the authentication project, Project B is responsible for managing user-related functionalities, and Project C handles restaurant-related operations. In Project A, I have created a custom user model to suit my authentication requirements. Now, I want to utilize this custom user model to access the APIs of both Project B and Project C. How can I achieve this integration between the projects? Specifically, I would like to accomplish the following: Enable user authentication: I want to use the custom user model defined in Project A to authenticate users when they access the APIs of Project B and Project C. Share user information: I need to access user information from Project B and Project C using the custom user model defined in Project A. This includes retrieving user details, updating user profiles, and performing user-related operations. Maintain consistency: It is essential to ensure that any changes made to the custom user model in Project A are reflected across all projects, including Project B and Project C. Here is my Custom user Model from Project A. import uuid from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.db import … -
RegisrationError in Django Algolia for multiple indices of the same model
How do I use the raw_search with a specific index after implementing multiple indices in Django Algolia? When I perform it like raw_search(VideoPublishIndex, "", query_params) where VideoPublishIndex is one of the indices of multiple indices for a specific model, it shows a RegistrationError, ...is not registered with Algolia engine. Also, can you please confirm, if we should be registering the meta index in the apps.py file? The error is show below: -
getattr(): attribute name must be string?
My models.py class Simple(models.Model): class Inner(models.TextChoices): a = 'small','Small' b = 'medium','Medium' c = 'large','Large' id = models.UUIDField(primary_key=True,default=uuid.uuid4, editable=False) name = models.CharField(max_length=200) size = models.TextField(choices=Inner.choices,default='medium', db_index=True) When use admin interface to add... TypeError at /admin/main/simple/add/ getattr(): attribute name must be string -
Is there a way to start an SQS listener alongside a Django web server on Elastic Beanstalk without causing the main thread to stop on AWS?
I am trying to set up a SQS listener that works alongside my django web server which is hosted on AWS Elastic Beanstalk. So far everything that I have tried has caused the main thread to just stop. I have tried threading (daemon & not daemon), I have tried async. I am not sure what else to try. The class attached works fine, I need to find a way to start it when django starts. My Class to listen to SQS import json import logging import boto3 # This is a Python class that listens to an Amazon Simple Queue Service (SQS) queue and handles # messages received. class SQSListener: def __init__(self, queue_url): self.queue_url = queue_url self.should_quit = False def start(self): self.sqs = boto3.client('sqs', region_name='us-west-2') while not self.should_quit: response = self.sqs.receive_message( QueueUrl=self.queue_url, MaxNumberOfMessages=1, WaitTimeSeconds=20 ) if 'Messages' in response: for message in response['Messages']: try: self.handle_message(message) except Exception as e: logging.error(f"Error processing message: {e}") self.sqs.delete_message( QueueUrl=self.queue_url, ReceiptHandle=message['ReceiptHandle'] ) def handle_message(self, message): # Override this method in a subclass to handle the message pass def stop(self): self.should_quit = True # This class creates a LogMessage object in Django's models based on a message received from an # SQSListener. class LogListener(SQSListener): def handle_message(self, … -
How to parse value from key in django template
First i want to explain what i want to achieve. at first this my query at view invoices = vendor.invoices.order_by('-due_date') this is the relevant model : class Booking(model.Models): ... invoice = models.ForeignKey('invoices.Invoice', related_name="bookings", on_delete=models.CASCADE, blank=True, null=True) POD_RETURN_STATUS = Choices( (1, 'on_driver', 'On Driver'), (2, 'taken_by_recipient', 'Taken by Recipient'), ... ) pod_return_status = models.PositiveSmallIntegerField(choices=POD_RETURN_STATUS, blank=True, null=True) whats new is i want to add the pod_return_status in template using invoice query. So like {% for invoice in invoices %} ... <td>{{ invoice.bookings.first.pod_return_status }}</td> {% endfor %} but of course it increases the number of query. at first i use prefetch_related but it seems to added more query. So after consulting with chatGPT this is my updated_query: invoices = vendor.invoices.order_by('-due_date').annotate( pod_return_status=Subquery( Booking.objects.filter(vendor_invoice=OuterRef('pk')).values('pod_return_status')[:1] ) ) it looks good on query numbers, but when i want to parse in template like this <td>{{ invoice.pod_return_status }}</td> it display the number like 1,2. what i want to display is the value of it like, 'On Driver' etc. Since im using model_utils.Choice, usually to display in template i use booking.get_field_name_display. but since the pod_return_status is acquired from annotation, not from the parents model. i cant use that. what im trying is to parse "POD_RETURN_STATUS": Booking.POD_RETURN_STATUS, to context_data so … -
Strategies for Integrate Webpack 5 into a Typical Django Project
I currently use Django Pipeline, which I want to remove and switch to using Webpack 5. I've made some headway in learning Webpack but am currently trying figure out the best project file structure and workflow. A typical Django project file structure like this: ├── django_project │ ├── accounts │ │ ├── migrations │ │ ├── static │ │ │ ├── accounts │ │ │ │ ├── css │ │ │ │ │ ├── custom.css │ │ │ │ │ └── another.css │ │ │ │ ├── img │ │ │ │ │ ├── something.png │ │ │ │ │ └── default.jpg │ │ │ │ ├── js │ │ │ │ │ ├── index.js │ │ │ │ │ └── custom.js │ │ │ │ └── scss │ │ │ │ ├── bootstrap.scss │ │ │ │ └── _custom.scss │ │ ├── templates │ │ ├── __init__.py │ │ ├── admin.py │ │ ├── apps.py │ │ ├── forms.py │ │ ├── models.py │ │ ├── tests.py │ │ ├── urls.py │ │ └── views.py │ ├── anotherapp │ │ ├── migrations │ │ ├── ... │ ├── django_project │ │ ├── __init__.py │ │ ├── asgi.py │ │ … -
Issue with combining data from multiple Django apps into a single form option in admin back office
I'm a fairly novice developer, but I'm aiming to master Django by developing a multi-tenant SaaS application that lets users create their own online stores. I'm still at the beginning of the project, but I've already run into a problem that's blocking me. My aim is to offer basic categories common to all users, while allowing them to create their own customized categories to classify their products. To achieve this, I've set up a multi-tenant architecture with Django-tenants, where each user has his own subdomain, store and categories. However, I'm having trouble grouping shared and custom categories in the user administration interface form, just where they can add a product (and choose the related category). I want users to be able to choose the category of their products from a list that includes both, shared categories and their own custom categories. I've tried several approaches, including the use of ManyToMany fields and custom widgets, but so far I haven't managed to get the desired result. Shared categories are not properly integrated into the category selection field, which limits the functionality of my application. If you have any suggestions, ideas or pointers on how best to solve this problem and group … -
two django user types
How do you create a doctor and a patient as users in your Django Python project with one view? how do I go about creating the two users? I have tried the role one but it is not working. please if you have tried another one let me see how you did it. -
"SHORT_DATETIME_FORMAT" and "SHORT_DATE_FORMAT" don't work in Django Templates while "DATETIME_FORMAT", "DATE_FORMAT" and "TIME_FORMAT" do
I use DateTimeField(), DateField() and TimeField in MyModel class as shown below. *I use Django 4.2.1: # "models.py" from django.db import models class MyModel(models.Model): datetime = models.DateTimeField() # Here date = models.DateField() # Here time = models.TimeField() # Here def __str__(self): return "MyModel" Then, I set DATETIME_FORMAT, DATE_FORMAT and TIME_FORMAT and set USE_L10N False to make DATETIME_FORMAT, DATE_FORMAT and TIME_FORMAT work in settings.py as shown below: # "settings.py" LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = False # Here USE_TZ = True DATETIME_FORMAT = "m/j/Y, P" # 10/25/2023, 2:30 p.m. # Here DATE_FORMAT = "F jS, Y" # October 25th, 2023 # Here TIME_FORMAT = "H:i:s" # 14:30:15 # Here Then, from a MyModel objcet, I get datetime, date and time and pass them to index.html in test() in views.py as shown below: # "views.py" from django.shortcuts import render from .models import MyModel def test(request): obj = MyModel.objects.all()[0] return render( request, 'index.html', {"datetime": obj.datetime, "date": obj.date, "time": obj.time} ) Then, I show datetime, date and time in index.html as shown below: # "index.html" {{ datetime }}<br/> {{ date }}<br/> {{ time }} Now, all DATETIME_FORMAT, DATE_FORMAT and TIME_FORMAT work according to browser as shown below: 10/25/2023, 2:30 … -
How to save each user's index from Llama index in chatGPT clone app
I am trying to make a chatGPT clone that can answer on external data (private data) using React, Django, OpenAI API, PostgreSQL, and Llama index, precisely speaking, in context learning. Then, my question is, how can I save each user's data (= index in the context of llama index)to PostgreSQL database? I Would like to know which method to store the data in the database is suitable in this case. I find it difficult to store a file or a folder to the database... -
How do I calculate the total number of likes for a user's posts in Django?
I'm working on a Django project and I'm trying to calculate the total number of likes for a user based on their posts (i.e if a user has post with 10 likes and another with 5, the total likes must display 15) . I've tried various approaches, but I haven't been able to get it working. Here is my models.py: class User(AbstractUser): username = models.CharField(...) first_name = models.CharField(...) last_name = models.CharField(...) email = models.EmailField(...) bio = models.CharField(...) ... class Post(models.Model): author = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) text = models.CharField(max_length=280) created_at = models.DateTimeField(auto_now_add=True) likes = models.ManyToManyField(User, related_name="user_post") def total_likes(self): return self.likes.count() class Meta: ordering = ["created_at"] And here I am trying to display the total number of likes for all posts from a specific user inside this html file (user profile): ... <p>Total likes: {{ post.likes.all.count }} </p> ... views.py @login_required def show_user(request, user_id): try: user = User.objects.get(id=user_id) posts = Post.objects.filter(author=user) except ObjectDoesNotExist: return redirect('user_list') else: return render(request, 'show_user.html', {'user': user , 'posts' : posts, 'request_user': request.user}) Here's what I've tried so far: Initially, I attempted to use the {{ post.likes.all.count }} template tag to display the total number of likes for each post. However, this didn't work as it didn't return … -
Why does Django raise a NoReverseMatch error when using the 'entry' iterator in a For loop and url method?
NoReverseMatch at / Reverse for 'entry' with keyword arguments '{'title': ''}' not found. 1 pattern(s) tried:['wiki/(?P[^/]+)\Z'] Line 12. index.html {% for entry in entries %} <li><a href="{% url 'entry' title=entry %}">{{entry}}</a></li> I am trying to print a list of entries with their links, but Django complains about the iterator 'entry' in the For cycle, it can actually print the elements of the list, but when using the url django method, it won't render the page 'cause that error. urls.py The path: path("wiki/str:title", views.entry, name="entry"), views.py Please a hand. -
Django DRF Serializer slice amount in list of nested field based on user
I want to ask how to slice a nested lists in DRF. I have models Store, Manager, Products. Serializer returns store object with a nested fields. What I want to do is to slice the values, to NOT return all, just to return Store, with top 3 managers and top3 products for each manager. And to do this based on User, if this is supervisor, then return full list, if manager, then only limited. I guess anyway I need to use different serializer for each use type, but how to slice nested value, that only return top 3? Kind regards, -
Django strange static behavior
I launched the small Polls app from Django tutorial here: https://docs.djangoproject.com/en/4.1/intro/tutorial06/ The first time i wrote it, all worked fine. Then I tried to add the same style to all other html files in the same dir as index.html: results.hmtl, votes.html and detail.html and then the strangest thing happened. No styles were added to these files also when i tried to change the style of polls/static/polls/style.css , nothing happened. I even renamed the style.css and the styles added to index.html remained unchanged. This means django looks for styles elsewhere. So where is this place? My settings are standard: settings.py: STATIC_URL = 'static/' STATIC_ROOT = "" index.html: {% load static %} <link rel="stylesheet" href="{% static 'polls/style.css' %}"> urls.py: from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('polls/', include('polls.urls')), path('', include('polls.urls')), path('admin/', admin.site.urls) ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) No effect whatsoeveer. I read the documentation, read comments here, nothing flashes, so I'm asking here, hoping for a chance to repair my static. Thanks! -
Integrating Firebase authentication with Django (DRF)
I am developing a Django (DRF)/React web application and have integrated Firebase authentication using the email/password provider. The application requires additional user data, and I aim to link the Firebase user database with the Django user model. The primary objective is to implement a secure and efficient authentication system. Workflow: Web client: Users sign up with their email and password, followed by the receipt of a verification email. Web client: Retrieve the ID token and send it, along with extra user data (e.g., first name, last name, organization, role), to the server. Server: Verify the ID token and authenticate the request using the FirebaseAuthentication class. Server: Check if the user exists in the Firebase database. Server: Create a user record in the Django user model if the user exists, ensuring data consistency between Firebase and Django. I have implemented a Django authentication backend using the FirebaseAuthentication class, as shown below: default_app = initialize_app() class FirebaseAuthentication(BaseAuthentication): def authenticate(self, request): auth_header = request.META.get("HTTP_AUTHORIZATION") if not auth_header: raise NoAuthToken("No auth token provided") id_token = auth_header.split(" ").pop() decoded_token = None try: decoded_token = auth.verify_id_token(id_token) except Exception: raise InvalidAuthToken("Invalid auth token") if not id_token or not decoded_token: return None try: uid = decoded_token.get("uid") except Exception: … -
how to create dynamic and interactive(clickable) collapsible topology graph using django
how to create dynamic and interactive(clickable) collapsible topology graph using django i have 3 csv files. 1 icon folder for png files. 1- relational object csv such as below SName|TName|SIcon xxxxx| |M yyyyy|xxxxx|F zzzzz|xxxxx|F aaaaa|yyyyy|D bbbbb|yyyyy|E .... .... 2-major problem csv file enter code here PName|Occtime|ClTime bbbbb|12.12.22| bbbbb|13.05.23|02.06.23 yyyyy|01.06.23|04.06.23 zzzzz|02.03.23| .... .... 3-information csv file PName|LastEvent|Createdby|solution|etc... bbbbb|12.12.22|danaaaaaaa|fromchatg|bla bla... ccccc|11.05.23|dsadadadsa|fromstackov|bla bla.. ..... ..... I want to draw graphs by reading files. if ClTime is not blank in problem csv files i want to change icons's circle colors. also I want to give some informations from the information file when someone clicks any icon. Objects should be static on the page (user should not move objects around on the page). objects should not oscillate. I have little django very little js ,html knowledge but i know python. I searched on the internet, what can I use for this? they suggest treant.js , d3.js, vis.js, networkx. I tried it in sample data but I didn't get the result what I wanted. I don't expect you to give the code. what is the correct method? where should i start and how should i sort it? I created some charts using treantjs. but I couldn't … -
Python/flask/django. I want to make a program similar to discord/teamspeak 3 using django/flask. Question below:
Which libraries should be used in order to make voice chats like in discord/teamspeak and how can this be implemented in the program code (by clicking on the voice. chat a person enters it)? I made text chats only for my messenger, but I didn't find anything for voice chats