Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problems with automatic pagination in Django, how to fix duplicate posts?
The problem is that duplicated posts appear during automatic pagination. If the loop {% for post in post_lists %} in the home.html template specifies the output of 5 published posts, then during automatic pagination, duplicates of these 5 published posts are added from the home_list.html template, which is incorrect. Automatic pagination works correctly and displays all published posts properly. The issue only lies with the duplication of the first five published posts; the rest of the posts are not duplicated and are displayed correctly. How to fix this? home.html: {% for post in post_lists %} <div class="post_content" id="post_content"> <!----code for displaying posts goes here----> </div> {% endfor %} <div id="pagination-loader" class="pagination_pages" data-page="1"></div> </div> <script> $(document).ready(function(){ var loadedPage = 1; // Variable to store the loaded page number // Function to load the next batch of posts function loadNextPage() { // Perform an AJAX request to the server var nextPageUrl = '/load-posts/?page=' + loadedPage; console.log("Next page URL:", nextPageUrl); $.ajax({ url: nextPageUrl, type: 'GET', dataType: 'json', success: function(response) { console.log("Response from server:", response); // Check for post data in the JSON response if (response.posts) { // Add HTML with posts to the end of the container $('#post_contenter').append(response.html_posts); // Check if there are … -
django migrate from CIEmailField to collation
I did upgrade from django version to 4.2.8 and then the CIEmailField() is deprecated. I used this CIEmailField on the email field of an user. So I had to change to: email = models.EmailField(unique=True, db_collation="case_insensitive") So the migration is like this: operations = [ CreateCollation( "case_insensitive", provider="icu", locale="und-u-ks-level2", deterministic=True, ), migrations.AlterField( model_name="user", name="email", field=models.EmailField(db_collation="case_insensitive", max_length=254), ), ] But before this changement, with CIEmailField I would .get() an user with this email "test@test.com" or "TEST@test.com". With the case_insensitive collation I made it work only by setting "deterministic=False". But with that, the SQL's LIKE is not working. So every Viewset with "email" in "search_fields" wont work. To make it work, I only found this solution: class UserAdmin(BaseUserAdmin): search_fields = ("email_deterministic", ...) ... def get_queryset(self, request: HttpRequest) -> QuerySet[User]: return ( super() .get_queryset(request) .annotate( email_deterministic=Collate("email", "und-x-icu"), ) ) So I have to do that EVERYWHERE on the App when I have an user to search by his email. But the App is big. Is there any other solution for this? -
Creating Azure B2B login system with Vue.js frontend & Python Django backend
I'm working on a full stack application using Vue.js for the frontend and Python Django for the backend. Now I want to set up my login system based on Microsoft Entra for my tenant (B2B). As my website is a SPA, my initial thought was to set it up with MS docs for public client. See also here. I've got it working. However, as I have a webapp with backend, this approach would be more suitable and safe (right!?). I'm trying to implement this logic, but as this logic is rendering the frontend from the python files I'm confused (as i'm rendering and organizing my front-end logic from the Vue.js side). My question is, what would be the best approach for my application, and how to proceed? I'm aware that my question is broad, but I'm really stuck... Implemented this logic successfully, but this approach is probably more safe/suitable. -
Sending emails in django using smtp
on my site i am trying to reset my password by e-mail using smtp but when i send a password change request i get this error: here is my settings.py : EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'expresstest177@gmail.com' EMAIL_HOST_PASSWORD = "ibuc pvmq fkgb acah" EMAIL_USE_TLS = True EMAIL_USE_SSL = False DEFAULT_FROM_EMAIL = EMAIL_HOST_USER SERVER_EMAIL = EMAIL_HOST_USER EMAIL_ADMIN = EMAIL_HOST_USER and urls.py if needed: urlpatterns = [ path('password-reset/', auth_views.PasswordResetView.as_view( template_name='main/password_reset_form.html', email_template_name='main/password_reset_email.html', success_url=reverse_lazy('user:password_reset_done')), name='password_reset'), path('password-reset/done/', auth_views.PasswordResetDoneView.as_view(template_name='main/password_reset_done.html'), name='password_reset_done'), path('password-reset/confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view( template_name='main/password_reset_confirm.html', success_url=reverse_lazy('user:password_reset_complete')), name='password_reset_confirm'), path('password-reset/complete/', auth_views.PasswordResetCompleteView.as_view(template_name='main/password_reset_complete.html'), name='password_reset_complete'), ] what could be the problem? -
Import CSV file from React front end to Django/Python backend proving unreliable
I am trying to get data from a csv file that is uploaded via a ReactJs front end and then import it into a sqlite database in a Django/Python backend. I am trying to use the same code for several different imports and I have at least two cases that work but when I try to replicate the code, it is not working. It does seem that a csv generated from Excel or from another system does work but I have a mac and if I try to edit the csv either using my VS Code editor or using Numbers (but exporting as a csv) the file then doesn't work. If I inspect the file in VS code though, I can't see any difference between the ones that work and the ones that do not. All are in utf. Is this a problem with the csv? And is there code I can add to diagnose that... and maybe rectify? FRONTEND: import axios from 'axios' import { formatTimeDate } from '../../lib/helpers' class CSVDataLoader extends Component { constructor() { super() this.state = { loading: false, updated: '' } this.handleSubmitData = this.handleSubmitData.bind(this) this.handleFile = this.handleFile.bind(this) } handleFile (e) { e.preventDefault() const fileToUpload = … -
Issue with Django --> Apache WSGI deployment
I have a django app running in VS Code 1.86.2 on a Debian 12 machine using Python 3.11.2. I'm working on a test deployment to Apache 2.4.57 and mod_wsgi 4.9.4. I've been working through docs from Apache and Django. At this point I am able to load html documents from the deployed site, but the Django template tags are not being processed. For example I see the below text in the browser. {% extends "base.html" %} {% block title %}my app{% endblock %} {% block content %} {% csrf_token %} Record Lookup Search Key: {% endblock %} I'm new to the Django and Apache world so hoping for some guidance on where to start diagnosing this issue. Any guidance is much appreciated! -
Should i use GET or POST for request with body in DRF?
I am relatively new to the web development and I am writing backend for webapp for practicing chemical elements and compounds and their formulas in our school. I am using Django and Django Rest Framework. I have encountered a dilemma where I can't decide whether to use GET method or POST method. In frontend it requests compounds and elements from the server with specific criteria. In this view, it recieves request with body (criteria), where are values requested_count, used_ids (to exclude already used compounds/elements), requested_groups, requested_elements (to exclude elements which may students don't know). Then, it filters the database to return the response. I have tested this many times and it is working correctly. My only question is, which method to use in this view. I know that POST should be used when I want to change something in the database and GET to just get query from the database. According to this I should use GET. But I want to send body with that request and that is something what POST typically does. What do you suggest? Thanks Here is the view code: class RequestCompoundsView(views.APIView): serializer_class = RequestCompoundsSerializer def get(self, request): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): # Get the … -
My djanco configuration fail to download images but store them in the db without occuring any error
I'm dealing with a problem I have since 2 days, i'm trying to store an image for a car website in a database other than my car one, the creation is successful, it appears in the database but when I try to store the same image in a folder of my application, whatever I try it simply doesn't work, here's my models : class Cars(models.Model): marque = models.CharField(max_length=60) modele = models.CharField(max_length=60) motorisation = models.CharField(max_length=60) couleur = models.CharField(max_length=60) carburant = models.CharField(max_length=60) annee_modele = models.IntegerField() kilometrage = models.IntegerField() nbr_porte = models.IntegerField() nbr_place = models.IntegerField() puiss_fiscale = models.IntegerField() #En chevaux fiscaux puiss_din = models.IntegerField() #En chevaux DIN a_vendre = models.BooleanField(default=True) class CarImage(models.Model): car = models.ForeignKey(Cars, related_name="images", on_delete=models.CASCADE) image = models.ImageField(upload_to='car_images/')models.py Post view : class manage_cars(View): parser_classes = (MultiPartParser, FormParser) def post(self, request, *args, **kwargs): c_serializer = car_serializer(data=request.POST) if c_serializer.is_valid(): car_instance = c_serializer.save() images = request.FILES.getlist('image') print(images) for image in images: image_path = handle_uploaded_image(car_instance, image) # Créer l'objet CarImage avec le chemin de l'image CarImage.objects.create(car=car_instance, image=image_path) return JsonResponse({"message": "Voiture et images sauvegardées avec succès"}, status=201) else: return JsonResponse(car_serializer.errors, status=400) serializers.py from rest_framework import serializers from .models import * class car_serializer(serializers.ModelSerializer): class Meta: model = Cars fields = "__all__"serializers.py settings.py : MEDIA_URL = "/media/" MEDIA_ROOT … -
When i implement Cronejob it looks like doesn't take effect
views: @scheduled_task def daily(request): signals.task_daily.send_robust(sender=None) return HttpResponse('ok') signals: from django.dispatch import Signal task_daily = Signal() commad: from django.core import management from django.dispatch import receiver @receiver(task_daily) def clear_old_sessions(*args, **kwargs): management.call_command("clearsessions", verbosity=0) print("Old sessions cleared") when i run and check if is working a have installed in on apps but sessions are not cleand and there is too much dump data -
What oauth 2.0 endpoint is used to validate a bearer token
I have an oauth 2 server implemented using django oauth2 provider. I am implementing the client credentials flow in an api. The client app POSTs to the oauth server's /token/ endpoint to get the access token. That is then sent to my api in the header. What endpoint should the api then call on the oauth server to validate this token, when using a back channel? -
Django view works slow
I have a view in my Django project: @permission_required('storage.add_iteminrelease') @transaction.atomic def add_item_in_release(request, id): release = get_object_or_404(Release, pk=id) if (request.method == 'POST'): add_item_in_release_form = ItemInReleaseForm(request.POST) if add_item_in_release_form.is_valid(): add_item_in_release_form.instance.release = release item = add_item_in_release_form.cleaned_data['item'] if item.count < add_item_in_release_form.cleaned_data['count']: messages.add_message(request, messages.ERROR, 'Кол-во выдачи не должно превышать ' + str(item.count)) return redirect('/releases/details/' + str(id) + '/') item.count -= add_item_in_release_form.cleaned_data['count'] item.save() item_in_release, create = ItemInRelease.objects.get_or_create(item=add_item_in_release_form.cleaned_data['item'], release=release, defaults={'count': add_item_in_release_form.cleaned_data['count']}) if not create: item_in_release.count += add_item_in_release_form.cleaned_data['count'] item_in_release.save() messages.add_message(request, messages.SUCCESS, 'Позиция успешно добавлена') return redirect('/releases/details/' + str(id) + '/') messages.add_message(request, messages.ERROR, add_item_in_release_form.errors.as_data()) return redirect('/releases/details/' + str(id) + '/') else: add_item_in_release_form = ItemInReleaseForm() return render(request, 'add_item_in_release.html', {'add_item_in_release_form': add_item_in_release_form, 'id': id}) and corresponding html template for it with some jQuery code: When I call that view, page is loading up to 10 seconds, but other pages loads instantly. Why that code is so slow? I don't understand. -
MultipleObjects returned when selecting a choice and creating an object for it
In my project I am using react for the frontend and django for the backend. I have the following models, which are related to the issue I am facing class Role(models.Model): ROLE_CHOICES = ( ('Recruiter', 'Recruiter'), ('Manager', 'Manager'), ('Business Development Partner', 'Business Development Partner'), ('Business Development Partner Manager', 'Business Development Partner Manager'), ('Account Manager', 'Account Manager'), ) role = models.CharField(max_length=50, choices=ROLE_CHOICES, null=True, unique=True) def __str__(self): return self.name class UserData(models.Model): fullName = models.CharField(max_length=255, blank=True, null=True) gender = models.CharField(max_length=10, blank=True, null=True) aadhaarNumber = models.CharField(max_length=12, blank=True, null=True) dateOfBirth = models.DateField(null=True, blank=True) maritalStatus = models.CharField(max_length=20, blank=True, null=True) emergencyContact = models.CharField(max_length=255, blank=True, null=True) address = models.TextField(blank=True, null=True) phoneNumber = models.IntegerField(validators=[MinValueValidator(0000000000), MaxValueValidator(9999999999)], blank=True, null=True) emailID = models.EmailField(validators=[EmailValidator()], blank=True, null=True) emergencyContactNumber = models.IntegerField(validators=[MinValueValidator(0000000000), MaxValueValidator(9999999999)], blank=True, null=True) jobTitle = models.CharField(max_length=100, blank=True, null=True) departmentName = models.CharField(max_length=100, blank=True, null=True) joiningDate = models.DateField(blank=True, null=True) employmentType = models.CharField(max_length=100, blank=True, null=True) prevCompany = models.CharField(max_length=255, blank=True, null=True) prevDesignation = models.CharField(max_length=100, blank=True, null=True) relevantSkills = models.TextField(blank=True, null=True) documentAcknowledged = models.BooleanField(default=False, null=True) pfUAN = models.CharField(max_length=100, blank=True, null=True) esiNO = models.CharField(max_length=100, blank=True, null=True) role = models.ForeignKey(Role, on_delete=models.SET_NULL, null=True, blank=True) def __str__(self): return self.fullName if self.fullName else "Unnamed User" class LoginDetails(models.Model): user_data = models.OneToOneField(UserData, on_delete=models.CASCADE, null = True) username = models.CharField(max_length=255, unique=True, null=True) password = models.CharField(max_length=255, null=True) # … -
Django channels: How to reference ForeignKey and their fields in async context?
I am right now converting a couple of Websocket-Handlers from WebsocketConsumer to AsyncWebsocketConsumer. There is one line that causes problems. The Sync version was: self.mydatacache['workernr'] = school.objects.get(id=myschool).tf_worker.id My first try for an async version was this: self.mydatacache['workernr'] = await school.objects.aget(id=myschool).tf_worker.id Second try: school_object = await school.objects.aget(id=myschool) tf_worker_object = await school_object.tf_worker self.mydatacache['workernr'] = tf_worker_object.id I tried many variations of this, but I always got the same error: You cannot call this from an async context I must be on the completely wrong track here. Any suggestions? -
Audio bytes chunks getting corrupted during streaming using Django and Websockets
I am trying to implement an audio streaming transcription service using django and websockets. The implementation works but the chunks get corrupted after some time like after tenth or eleventh chunk of transcription, while debugging, I discovered that the webm audio bytes extension was missing (which means some other metadata might also be missing in those chunks which makes me unable to transcribe those chunks. class TranscriptConsumer(AsyncWebsocketConsumer): """ Server side implementation of the audio streaming service """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.audio_buffer = b'' # Variable to store accumulated audio data I used the audio_buffer variable to concatenate all audio bytes chunks still in an effort to prevent the corruption of data because before using that variable to concatenate the chunks, I experienced the audio bytes corruption after the first chunk. I use below to receive and concatenate the chunks async def receive(self, text_data=None, bytes_data=None): if bytes_data: # Combine incoming bytes_data with the accumulated audio_buffer self.audio_buffer += bytes_data # Check if the combined data is sufficient for processing if len(self.audio_buffer) >= 10000: await self.process_audio() And below to transcribe the chunks # Split the combined data into chunks max_chunk_size = 1024 * 1024 # 1MB chunk size chunks = … -
How to have a forum in my Django website? [closed]
I want to have a forum on my Django website and I prefer to use the third-party packages. After doing some research I saw some packages like machina and Spirit and PyBBM https://django-machina.readthedocs.io/en/latest/getting_started.html The question is how can I make any of these packages to use another language like persian?(It's RTL) Or can I use the other methods like phpbb in my django project? -
How to manage different repositories for different clients with the same project?
Good morning, I have to manage a Django project where each client has small customizations, both in terms of apps and API endpoints. I would like to avoid having to manage too many branches for each individual customer: First solution In the .env file, add a field indicating the client CUSTOMER=customer1 #settings.py #... INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "rest_framework", "rest_framework_simplejwt", ] customer = os.getenv("CUSTOMER") if customer == "customer1": INSTALLED_APPS.append('custom_customer1') Secpnd solution Use various branches according to the client, with the various merge coming from master/main develop --> master --> customer1_develop --> customer1_master Which system do you recommend? -
Unable to see text in the dropdown list
So in my project I am using react for the frontend and django for the backend. I have the following model class Role(models.Model): ROLE_CHOICES = ( ('Recruiter', 'Recruiter'), ('Manager', 'Manager'), ('Business Development Partner', 'Business Development Partner'), ('Business Development Partner Manager', 'Business Development Partner Manager'), ('Account Manager', 'Account Manager'), ) role = models.CharField(max_length=50, choices=ROLE_CHOICES) def __str__(self): return self.name I have created the following view to get the role choices I have defined to the frontend @csrf_exempt def role_choices(request): roles = [role[1] for role in Role.ROLE_CHOICES] return JsonResponse(roles, safe=False) And this is the endpoint I created for it path('roles/', role_choices, name='roles_list'), Now in my frontend, I have a form, with one of the field being a role, which when clicked should show a dropdown list populated with the role choices (only pasting the required code here) <h2>Role</h2> <label> Select Role: <select name="role" value={userData.role} onChange={handleInputChange} > <option value="">Select</option> {roleOptions.map(role => ( <option key={role.id} value={role.role}> {role.role} </option> ))} </select> </label> <br /> <button type="submit" class="btn btn-default btn-sm">Submit</button> </form> </div> But I dont see the role options on the webpage I have logged the response I get when calling the endpoint and I see the role options being fetched The below code shows how I … -
How to register a custom RangeField in postgre db with django
I tried to follow the docs and this is what I came to: from django.db import models from django import forms from django.contrib.postgres.fields import RangeField from psycopg.types.range import Range from django.utils.translation import gettext_lazy as _ class TimeRange(Range): """Time interval.""" pass class TimeRangeFieldForm(BaseRangeField): """Form for time interval.""" default_error_messages = {'invalid': _('Enter two valid times.')} base_field = forms.TimeField range_type = TimeRange class TimeRangeField(RangeField): """Time interval field.""" base_field = models.TimeField range_type = TimeRange form_field = TimeRangeFieldForm def db_type(self, connection): return 'timerange' But there is also that range_register() thing and I just don't get how to use it in code. And when I try to do migrations I get django.db.utils.ProgrammingError: type "timerange" does not exist LINE 1: ...IDENTITY, "days" smallint[7] NOT NULL, "interval" timerange .... Please help me understand how to create custom range field. Also I don't get how there is DateTimeRangeField and DateRangeField but no TimeRangeField... -
how can i fix this :ModuleNotFoundError
I'm working on a django project as an editor I use vscode I installed a virtual environment and installed django without problem. I also installed the qrcode module, but the problem arises when I try to import it. I have this message: ModuleNotFoundError: No module named 'qrcode'. when I do a pip freeze, I indeed find the qrcode module installed, Help me please I tried to install it in settings.py in the install applications, but still nothing -
Multiplying the difference between today and a DateField by a number using Django Models
I'm trying to get the difference in days between the date each row of my table The current date So I can then multiply it by a number. However I keep getting errors and exceptions. I searched Google, the Django docs, but couldn't find how. I even asked ChatGPT and Codeium but they keep giving completely wrong advice and direction. If I over-simplify my model and query, There is the History table with all the rows containing the symbols, their type and their rank on a specific date. class History(models.Model): date = models.DateField() type = models.CharField(max_length=255, choices=["type1", "type2", "type3"]) symbol = models.CharField(max_length=10) rank = models.PositiveSmallIntegerField() rating = models.DecimalField(max_digits=3, decimal_places=2) Then with this query, I'm trying to get all the rows of "type1", then getting the difference in days between today and their date to multiply this amount by their rank: compiled_type = ( History.objects .values("symbol", "type") .filter(type="type1") .annotate(days_difference_delta=datetime.now().date() - F('date')) # This works and returns a TimeDelta .annotate(score=ExpressionWrapper((datetime.now().date() - F('date')) * F('rank')), output_field=IntegerField) # Getting a ton of errors and exceptions whatever I put on this line .order_by("-score").all() ) Again it's over-simplifying as this is just the first step of a more complex calculation where I would group all rows … -
django add filtes in template is not work expectedly
I am a Django and Python beginner, and I encountered a problem while using Django. I hope to use a filter in the template to get the string I need, but the result below is not what I expected. # filter definition @register.filter def to_class_name(obj): return obj.__class__.__name__ # HTML template for UpdateView (This template will be used by multiple models.) # object = Order() {{ object|to_class_name }} #reulst: Order {{ 'wms'|add:object|to_class_name }} #result: str, expect: object I roughly understand that the issue lies with the order, but it seems I can't add parentheses to modify it. {{ 'wms'|add:(object|to_class_name) }} #cause SyntaxError Is there any way to solve this problem? Or is there a better way to determine the page data I need to output based on the model class when multiple models share one template? Thank you all. -
Download files uploaded to the "static" folder - Django
I need the .wav file that is created in the "static" folder to be able to be downloaded via a link inserted via HTML or viewed via FileResponse. I tried things like: <a href="{% static 'files/{{ filename }}' %}">Download: {{ filename }} </a> But this didn't work because it doesn't find the resource. -
Django: "Select which login to update" dialog
I am creating a django app that has a part to change user's password with a form. The form gets old_password & new_password from user and I handle that in views.py file. My problem is when I submit the form, browser showing me a dialog that says "Select which login to update" and listed the django.contrib.auth.models.User's data. I didn't write anything in my views.py file. you can see that bellow. views.py @login_required def profile_home(request): user = User.objects.get(username=request.user.username) # Find original user object if request.method == 'POST': if request.POST.get('password'): form_change = ChangePasswordForm(request.POST) if form_change.is_valid(): data = form_change.cleaned_data return redirect('panel:login_home') else: # something for other form else: # GET return Dialog image: -
To render contents for a website frontend from django backend
Im going to build a website in angular and I need to render the contents from the backend on MySQL I need help for designing a data model for the website How to plan the data model for content management for a website from the backend. I need a clear explanation for database structure. -
How to change status field automatically from 1 to 0 when end_time is reached
This is my Auction model. class Auction(models.Model): auction_id = models.AutoField(primary_key=True) crop = models.ForeignKey(Crop, on_delete=models.CASCADE) image = models.ImageField(upload_to="crop-image") farmer = models.ForeignKey(User, on_delete=models.CASCADE, limit_choices_to={'user_type': 'farmer'}) creation_time = models.DateTimeField(auto_now_add=True) end_date = models.DateField() end_time = models.TimeField() status = models.BooleanField(default=True) qty = models.IntegerField() unit = models.CharField(max_length=10, choices=[('kg', 'Kilograms'), ('tonne', 'Metric Tons'), ('bushel', 'Bushels'), ('crate', 'Crates')]) hammer_price = models.IntegerField() description = models.CharField(max_length=200) payment = models.BooleanField(default=False) class Meta: verbose_name_plural = "Auctions" def __str__(self): return self.crop.title When combined end_date and end_time is reached, status which is by default set to 1 on auction creation should be changed to 0.