Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Filter a field in a form set (Django)
How to filter a field on a form so that items created by another user are not ordered I have a set of forms from django import forms from django.forms.models import inlineformset_factory from .models import Course, Module ModuleFormSet = inlineformset_factory(Course, Module, fields=['title', 'section', 'description'], extra=2, can_delete=True) In the form in the list of sections, sections created by another teacher appear. How to configure sections to be allocated only to the user who creates modules? How to write a field filter on a form? -
Making migrations for app models moved to another directory that's not their default creation directory
This is my folder structure backend server apps #directory I created endpoints #my app In settings.py INSTALLED_APPS[ ....... 'apps.endpoint' ] When I run python3 manage.py make migrations I'm receiving a ModuleNotFoundError: No module named 'endpoints' -
Django-allauth could not login existing user
I use Django 5 and django-allauth. Currently I do not use any advanced features of this library, the only reasons I use it: It has a well-developed workflow with email opt-in feature It can support both username and email based authentication out of the box. Here is my settings, related to the library: # django-allauth specific settings for regular accounts not including the social authentication part. ACCOUNT_AUTHENTICATION_METHOD="username_email" ACCOUNT_CHANGE_EMAIL=True ACCOUNT_CONFIRM_EMAIL_ON_GET=False ACCOUNT_EMAIL_REQUIRED=True ACCOUNT_EMAIL_VERIFICATION="mandatory" ACCOUNT_UNIQUE_EMAIL=True ACCOUNT_DEFAULT_HTTP_PROTOCOL="https" ACCOUNT_MAX_EMAIL_ADDRESSES=2 ACCOUNT_LOGOUT_ON_PASSWORD_CHANGE=True ACCOUNT_LOGIN_ON_PASSWORD_RESET=True ACCOUNT_SESSION_REMEMBER=True ACCOUNT_USERNAME_REQUIRED=False ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE=False # Our specific signup and login forms with special styling ACCOUNT_FORMS = {'signup': 'user_profile.forms.CustomSignupForm', 'login': 'user_profile.forms.CustomLoginForm'} The only role of CustomLoginForm is to have customized css: from allauth.account.forms import LoginForm class CustomLoginForm(LoginForm): def __init__(self,*args, **kwargs): super().__init__(*args, **kwargs) # The parent class does similar. The only reason we had to make custom loginform # to handle bootstrap css self.fields["login"].widget.attrs.update({"class": TEXT_INPUT_CLASS}) if app_settings.AuthenticationMethod == AuthenticationMethod.USERNAME: self.fields["login"].widget.attrs.update({"placeholder": "Felhasználónév", "autocomplete": "username"}) elif app_settings.AuthenticationMethod == AuthenticationMethod.EMAIL: self.fields["login"].widget.attrs.update({"placeholder": "Email cím", "autocomplete": "email"}) else: self.fields["login"].widget.attrs.update({"placeholder": "Email cím / felhasználónév", "autocomplete": "email"}) self.fields["password"].widget.attrs.update({"class": TEXT_INPUT_CLASS, "placeholder": "Add meg a jelszavad", "autocomplete": "password"}) When I start my development server to see why I can not login with existing username and password, I used the Debug Toolbar to see SQLSs generated by … -
How to use utilize nested ArrayAgg in Django?
These are my models class TimeSheet(CommonModel): employee = models.ForeignKey( "employee.Employee", related_name="timesheets", on_delete=models.PROTECT ) project = models.ForeignKey( "core.Project", related_name="employee_timesheets", on_delete=models.PROTECT ) timesheet_date = models.DateField() clock_in_time = models.DateTimeField() clock_out_time = models.DateTimeField(null=True) class TimesheetEquipment(CommonModel): equipment = models.ForeignKey( "equipment.Equipment", on_delete=models.PROTECT, related_name="timesheet_equipments", ) resource_code = models.CharField(max_length=150) resource_name = models.CharField(max_length=511) rate = models.DecimalField( max_digits=30, decimal_places=decimal.ACCEPTED_DECIMAL_PLACE ) unit = models.CharField(max_length=63, default="Hour") timesheet = models.ForeignKey( "timesheet.Timesheet", on_delete=models.CASCADE, related_name="timesheet_equipments", ) equipment_attachments = models.ManyToManyField( "costcode.ResourceCode", related_name="timesheet_equipments", blank=True, through="timesheet.TimesheetEquipmentAttachment", help_text="Other Resources to be attached with this requirement", ) class TimesheetEquipmentAttachment(models.Model): timesheetequipment = models.ForeignKey( TimesheetEquipment, on_delete=models.CASCADE, related_name="timesheetequipmentattachments", ) resource = models.ForeignKey( "resource_management.CostSheetResource", related_name="timesheetequipmentattachments", on_delete=models.PROTECT, null=True, ) resource_code = models.CharField(max_length=150) resource_name = models.CharField(max_length=150) This is my queryset to get all the timesheet along with its equipments from django.db.models.functions import JSONObject from django.contrib.postgres.aggregates import ArrayAgg timesheets = ( TimeSheet.objects.filter(project_id=project_id, timesheet_date=date) .select_related("employee") .prefetch_related( "timesheet_equipments", "timesheet_equipments__timesheetequipmentattachments", ) .values("id") .annotate( timesheet_date=F("timesheet_date"), clock_in_time=F("clock_in_time"), clock_out_time=F("clock_out_time"), timesheet_equipments=ArrayAgg( JSONObject( equipment=F("timesheet_equipments__equipment_id"), equipment_name=F( "timesheet_equipments__equipment__equipment_name" ), resource_code=F("timesheet_equipments__resource_code"), resource_name=F("timesheet_equipments__resource_name"), rate=F("timesheet_equipments__rate"), unit=F("timesheet_equipments__unit"), ), distinct=True, ), ) .values( "id", "timesheet_date" "clock_in_time", "clock_out_time", "timesheet_equipments", ) .order_by("-timesheet_date") .distinct() ) this is the queryset that i am trying to get all the timesheets along with its all equipments and each equipments should have all of there equipment attachments if exists. But this did not worked. Any help would be highly … -
Issue with Celery Not Receiving Tasks - Django Ubuntu
I'm experiencing an issue with Celery where it doesn't respond automatically upon system boot. Here's a breakdown of my setup and the problem: Setup: Django project using Celery for asynchronous tasks. Celery workers configured with the @shared_task decorator. Using Redis as the broker with the CELERY_BROKER_URL set to 'redis://localhost'. Celery workers configured to run as a systemd service on Ubuntu. Problem: When the system boots up, Celery starts automatically, but asynchronous tasks are not executed. Manually starting Celery with the command home/ubuntu/.venv/bin/celery -A febiox.celery worker -l info -E works fine, and tasks are executed as expected. Checking the status of Celery service with sudo systemctl status celery.service shows that the service is active and running. However, when attempting to inspect active Celery nodes with celery -A febiox.celery inspect active, I get the error message Error: No nodes replied within time constraint. Interestingly, running the same command after manually starting Celery returns the expected result showing the correct node. Systemd Service Configuration: [Unit] Description=Celery Task Worker After=network.target [Service] Type=simple User=ubuntu WorkingDirectory=/home/ubuntu/febiox ExecStart=/home/ubuntu/.venv/bin/python3 /home/ubuntu/.venv/bin/celery -A febiox.celery worker -l info -E Restart=always StandardOutput=file:/var/log/celery/celery.log StandardError=file:/var/log/celery/celery_error.log [Install] WantedBy=multi-user.target Additional Information: Redis receives data when attempting to execute tasks. sudo systemctl reload celery.service doesn't produce any … -
"ORDER BY NOT ALLOWED IN SUBQUERIES OF COMPOUND STATEMENTS" IN DJANGO WHILE USING UNION FUNCTION
I'm new to Django and want to use this code: if "dashboard_filters_parent_checkbox" not in request.POST: # all_task_id=[t.id for t in tasks_no_assign.union(tasks_no_start).union(tasks_start).union(tasks_no_confirmed).union(tasks_confirmed)] #.union(sub_tasks_no_confirmed) # all_task_parent_id=[t.task_parent.id if t.task_parent and t.task_parent.id in all_task_id else 0 for t in tasks_no_assign.union(tasks_no_start).union(tasks_start).union(tasks_no_confirmed).union(tasks_confirmed)] #.union(sub_tasks_no_confirmed) # all_tasks_children_id=[t.GetAllTaskChildrenId for t in tasks_no_assign.union(tasks_no_start).union(tasks_start).union(tasks_no_confirmed).union(tasks_confirmed)] #.union(sub_tasks_no_confirmed) # all_tasks_children_id=[_id for id_set in all_tasks_children_id for _id in id_set ] all_task_id=tasks_no_assign.union(tasks_no_start).union(tasks_start).union(tasks_no_confirmed).union(tasks_confirmed).values_list('id',flat=True) #.union(sub_tasks_no_confirmed) all_task_parent_id=tasks_no_assign.union(tasks_no_start).union(tasks_start).union(tasks_no_confirmed).union(tasks_confirmed).values_list('task_parent__id',flat=True) #.union(sub_tasks_no_confirmed) all_task_parent_id = list(set(all_task_id) & set(all_task_parent_id)) # all_tasks_children_id=[t.GetAllTaskChildrenId for t in tasks_no_assign.union(tasks_no_start).union(tasks_start).union(tasks_no_confirmed).union(tasks_confirmed)] #.union(sub_tasks_no_confirmed) # all_tasks_children_id=[_id for id_set in all_tasks_children_id for _id in id_set ] all_tasks_children_id = list(set(all_task_id) - set(all_task_parent_id)) tasks_no_assign=tasks_no_assign.exclude(Q(pk__in=all_task_parent_id)&~Q(pk__in=all_tasks_children_id)) tasks_no_start=tasks_no_start.exclude(Q(pk__in=all_task_parent_id)&~Q(pk__in=all_tasks_children_id)) tasks_start=tasks_start.exclude(Q(pk__in=all_task_parent_id)&~Q(pk__in=all_tasks_children_id)) tasks_no_confirmed=tasks_no_confirmed.exclude(Q(pk__in=all_task_parent_id)&~Q(pk__in=all_tasks_children_id)) tasks_confirmed=tasks_confirmed.exclude(Q(pk__in=all_task_parent_id)&~Q(pk__in=all_tasks_children_id)) but I get this error: ORDER BY NOT ALLOWED IN SUBQUERIES OF COMPOUND STATEMENTS I now this error shown for using Union function but where is problem? how can I do and what is correct way? thanks in advance <3 but I get this error: ORDER BY NOT ALLOWED IN SUBQUERIES OF COMPOUND STATEMENTS I now this error shown for using Union function but where is problem? how can I do and what is correct way? thanks in advance <3 -
Django Templates - should I place HTML tags inside blocks of text subject to translation?
Is there any way to simplify the translation process when I have phrases with links and other HTML elements in them ? Currently I am breaking long phrases into multiple translate tags which don't translate properly the meaning of the whole phrase: <span class="text-sm"> {% translate "Please" %} <a class="inline font-semibold cursor-pointer text-blue-600 border-b-2 border-transparent hover:border-b-2 hover:border-blue-600" href="{% url "shop:login" %}"> {% translate "login" %} </a> {% translate "to place your order. If you don’t have an account yet, you can" %} <a class="inline font-semibold cursor-pointer text-blue-600 border-b-2 border-transparent hover:border-b-2 hover:border-blue-600" href="{% url "shop:register" %}"> {% translate "register" %} </a> {% translate "here." %} </span> I have thought about using blocktrans, but this will carry the html tags into the .po file and maybe even translate the applied Tailwind CSS classes: <span class="text-sm"> {% blocktrans %} Please <a class="inline font-semibold cursor-pointer text-blue-600 border-b-2 border-transparent hover:border-b-2 hover:border-blue-600" href="{% url "shop:login" %}"> login </a> to place your order. If you don’t have an account yet, you can <a class="inline font-semibold cursor-pointer text-blue-600 border-b-2 border-transparent hover:border-b-2 hover:border-blue-600" href="{% url "shop:register" %}"> register </a> here. {% endblocktrans %} </span> Is there a way of doing this properly so that we can translate the whole … -
Update existing data by django-rest-framework upload file
I am able to add data normally, but cannot update existing data. I can add a new entry, but I can't update entries with the same name in the imported data. What should I do? class CategoryUploadView(APIView): authentication_classes = [OAuth2Authentication] permission_classes = [AllowAny] parser_classes = [MultiPartParser] def post(self, request): file_obj = request.FILES['file'] decoded_file = file_obj.read().decode('utf-8').splitlines() reader = csv.DictReader(decoded_file) for row in reader: serializer = CategorySerializer(data=row) if serializer.is_valid(): serializer.save() else: return Response(serializer.errors, status=400) return Response({"message": "Data imported successfully"}, status=200) class CategorySerializer(serializers.ModelSerializer): class Meta: model=Category fields=['id', 'name'] def to_internal_value(self, data): data = data.copy() data['name'] = data.get('name', None).lower() return super().to_internal_value(data) class Category(models.Model): name = models.CharField(max_length=32, unique=True) description = models.CharField(max_length=255) update_on = models.DateField(auto_now=True) def __str__(self) -> str: return self.name -
Problem when doing a search with multiple results. NoReverseMatch
I am making a web application that uses the OpenLibrary API, using Django. In it I do a search within the API, if the results show more than one book, I get this error: NoReverseMatch at /search-results/ Reverse for 'book_detail' with arguments '('reina-roja-red-queen', 'Reina Roja / Red Queen')' not found. 1 pattern(s) tried: ['books/((?P[-a-zA-Z0-9_]+)/(?P[^/]+)+)'] My files are as follows: urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("search-results/", views.search_results, name="search_results"), path("books/<slug:slug>/<str:title>", views.book_detail, name="book_detail"), ] views.py from django.shortcuts import render, get_object_or_404, redirect from django.utils.text import slugify from books.api_library import search_book_by_author, search_book_by_title from .models import Book import requests import json def index(request): """ Index page """ if request.method == "POST": type_search = request.POST.get("type_search") search = request.POST.get("search") if type_search == "title": books_data = search_book_by_title(search).get("docs", []) elif type_search == "author": books_data = search_book_by_author(search).get("docs", []) if not books_data: books_data = [] request.session['search_results'] = books_data return redirect('search_results') return render(request, "books/index.html") def search_results(request): """ View to display search results """ search_results = request.session.get('search_results', []) books = [] for book in search_results: slug = slugify(book.get("title", "")) book_info = { "title": book.get("title", ""), "author": book.get("author_name", ""), "isbn": book.get("isbn", ""), "cover": book.get("cover", ""), "publisher": book.get("publisher", ""), "cover_url": f"https://covers.openlibrary.org/b/id/{book.get('cover_i', '')}-S.jpg", "description": book.get("description", ""), "publish_date": … -
Django REST - Updating or Creating object with foreign key reference
Document is the parent Model and LineItem is the child model with a foreign key reference to Document I am able to delete LineItem individually. However, I am unable to create or update individual LineItem as I keep getting a ValidationError stating 'document': [ErrorDetail(string='This field is required.', code='required') I have found a few workarounds but am wondering if there is a more standard way to solve this that I maybe overlooking class Document(models.Model): """ ORM representing Document object """ id = models.AutoField( primary_key=True, ) user = models.ForeignKey( User, on_delete=models.CASCADE, related_name='documents', ) class LineItem(models.Model): """ ORM representing line items in a document. """ id = models.AutoField( primary_key=True, ) document = models.ForeignKey( Document, on_delete=models.CASCADE, related_name='line_items', ) description = models.CharField( max_length=50, blank=True, db_default='', default='', ) user = models.ForeignKey( User, on_delete=models.CASCADE, related_name='line_items', ) serializers.py class LineItemSerializer(serializers.ModelSerializer): user = serializers.HiddenField(default=serializers.CurrentUserDefault()) class Meta: model = LineItem fields = '__all__' urls.py # Add a document line item path('api/document/<int:doc_pk>/line/', DocumentLineItemCreateAPI.as_view(), name='document-line-item-add-api'), # Edit a document line item path('api/document/<int:doc_pk>/line/<int:pk>/', DocumentLineItemUpdateAPI.as_view(), name='document-line-item-update-api'), views.py class DocumentLineItemUpdateAPI(generics.RetrieveUpdateDestroyAPIView): """ Unified view for retreiving, updating or deleting document line items """ serializer_class = LineItemSerializer def get_queryset(self): return LineItem.objects.all() def get_object(self): obj = get_object_or_404(self.get_queryset(), \ document_id=self.kwargs.get('doc_pk'), id=self.kwargs.get('pk')) return obj def destroy(self, request, doc_pk, pk, *args, … -
Cutting and pasting using jsPDF results in running out of memory
I have created a Django project called pdfClipper. It allows a user to select clips from an existing PDF file, reorder them in any order they wish, then it creates a new PDF file with those clips pasted in that order. It begins with opening a PDF file, which is uploaded in the static storage. Then, the user goes through each page, using sliders to get clips. Then, the screen where the user can choose how to reorder clips. Finally, the final screen shows where the new PDF file is created, using a progress bar to show how far along the process is. The problem is, if there are a lot of clips, the browser potentially runs out of memory. The following code is from the final page, titled "build.html". // this API gets data about the pdf file being clipped: // - the file name // - the maximum page width // - the maximum page height async function getFileData() { const response = await fetch("https://imcinnes31-pdfclipper.herokuapp.com/pdfclip/api/files?fileId={{fileId}}"); if (!response.ok) { throw new Error("HTTP error " + response.status); } return response.json(); } // this API gets data about each clip wanted from the file: // - the page where each clip … -
Can't upload images from flutter apps to Djnago rest framework
For my college project, I built an app, where I can update any kind of text info to Django rest API, but I can't send or upload any kind of media file from Flutter apps to Django. If anyone collaborated flutter with the Django rest framework please, help me with appropriate resources. I didn't find any resources to try to upload media files such as photos, pdf, videos, etc. -
Unexpected behaviour when calling serializer.create method, causes data loss in unrelated data (Django Rest Framework)
Im writing a tests for the serializer.create method. I prepared some data to pass it to the create method def create(self, validated_data): """ Passing in the restructured validated_data to the CostumUserCreate method. """ user_data = validated_data.get('user_data') profile_data = validated_data.get('profile_data') new_user = User.objects.create( user_data=user_data, profile_data=profile_data ) return new_user my test: def test_serializer_create(self): """ Tests the correct restructuring of the validated data within the CustomUserSerializer create method. """ data = {} user_data = { 'email': 'updated.email@GMAIL.com', # Not normalized 'password': 'blabla123' } profile_data = { 'first_name': 'Jay', 'last_name': 'Miller', 'position': self.position1 } data['user_data'] = user_data data['profile_data'] = profile_data serializer = serializers.CustomUserSerializer() user = serializer.create(data) print(f'USER DATA: {user_data}') print(f'PROFILE DATA: {profile_data}') when i try to print the user_data and profile_data now into the console it will be printed as an empty dictionary in the case of the user_data but not for the profile_data USER DATA: {} PROFILE DATA: {'first_name': 'Jay', 'last_name': 'Miller', 'position': <Position: Human Resource Specialist>} but as soon as i comment out the serializer.create method the user_data appears again in the terminal USER DATA: {'email': 'updated.email@GMAIL.com', 'password': 'blabla123'} PROFILE DATA: {'first_name': 'Jay', 'last_name': 'Miller', 'position': <Position: Human Resource Specialist>} i have no idea how this can even happen since the serializer.create … -
Database tuning for 1 million record
I have table which has 1 million record. And I show the data like this, simply show the data with ListView and pagenation from django.views.generic import ListView class ListSearchView(ListView): paginate_by = 10 form_class = None form = None ordering = "-created_at" sort_headers = None def get_initial(self): return self.request.GET.copy() def get_form(self): return self.form_class(self.get_initial()) def get_ordering(self): return self.request.GET.get("sort_by", self.ordering) def get_context_data(self, **kwargs): form = self.get_form() params = querydict_to_dict(self.request.GET.copy()) search_params = {k: v for k, v in params.items() if k != 'page' and k != 'sort_by'} query = {k: v for k, v in params.items() if k != 'page'} kwargs.update({ 'form': form, 'search_params': url_encode_params(search_params), 'query': url_encode_params(query), 'sort_by': query.get('sort_by', self.ordering), 'sort_headers': self.sort_headers }) return super(ListSearchView, self).get_context_data(**kwargs) def get_queryset(self): queryset = super().get_queryset() self.form = self.get_form() if self.form.is_valid(): created_date = self.form.cleaned_data.get('created_date') if created_date: start, end = created_date.split(DATE_RANGE_SEPARATOR) start_date = datetime.strptime(start, DATE_RANGE_FORMAT) end_date = datetime.strptime(end, DATE_RANGE_FORMAT) queryset = queryset.filter( created_at__gte=start_date.astimezone(pytz.UTC), created_at__lt=end_date.astimezone(pytz.UTC) ) status = self.form.cleaned_data.get('status', []) status = [s for s in status if s != ''] if status: queryset = queryset.filter( status__in=status ) return queryset class MessageListView(LoginRequiredMixin, ListSearchView): template_name = "message/index.html" model = Message def get(self, request, *args, **kwargs): return super(MessageLogView, self).get(request, *args, **kwargs) Now the load time is more than 2~3s, I would like to … -
On click function is not working in script
In product_detail.html: {% extends 'partials/base.html'%} {%load static%} {% block content %} <style> /* Basic Styling */ html, body { height: 100%; width: 100%; margin: 0; font-family: 'Roboto', sans-serif; } .containerbox { max-width: 1200px; margin: 0 auto; padding: 15px; display: flex; } /* Columns */ .left-column { width: 65%; position: relative; } .right-column { width: 35%; margin-top: 60px; } /* Left Column */ .left-column img { width: 70%; position: absolute; left: 0; top: 0; opacity: 0; transition: all 0.3s ease; } .left-column img.active { opacity: 1; } /* Right Column */ /* Product Description */ .product-description { border-bottom: 1px solid #E1E8EE; margin-bottom: 20px; } .product-description span { font-size: 12px; color: #358ED7; letter-spacing: 1px; text-transform: uppercase; text-decoration: none; } .product-description h1 { font-weight: 300; font-size: 52px; color: #43484D; letter-spacing: -2px; } .product-description p { font-size: 16px; font-weight: 300; color: #86939E; line-height: 24px; } /* Product Configuration */ .product-color span, .cable-config span { font-size: 14px; font-weight: 400; color: #86939E; margin-bottom: 20px; display: inline-block; } /* Product Color */ .product-color { margin-bottom: 30px; } .color-choose div { display: inline-block; } .color-choose input[type="radio"] { display: none; } .color-choose input[type="radio"] + label span { display: inline-block; width: 40px; height: 40px; margin: -1px 4px 0 0; vertical-align: … -
how to pass the query result in view.py to Bootstrap-table
i use pymysql to get data from my database conn = pymysql.connect( host='localhost', user='root', password='xxxxxxxxxx', database='TCR', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor, ) cur = conn.cursor() result = cur.excute('SELECT * FROM TCR') data = cur.fetchall() Then i return 'data' to my HTML file in HTML file i use Bootstrap-tabel to display my table. i notice that js part needs a .json file to fetch the data. such as: $('#table').bootstrapTable({ url: 'data1.json', columns: [{ field: 'id', title: 'Item ID' }, { field: 'name', title: 'Item Name' }, { field: 'price', title: 'Item Price' }] }) but i don`t want to use .json, i want to use the variable 'data' in js. How do I convert data to a form acceptable to bootstrap-table? i tried this <div id="data-container" data-query-results = {{ data }} ></div> <div id="reportTableDiv" > <table id="reportTable"></table> </div> <script type="text/javascript"> text = document.getElementById('data-container').getAttribute('data-query-results'); console.log(text) var datas = JSON.parse(text); but i got an error when i use JSON.parase() Uncaught SyntaxError: Expected property name or '}' in JSON at position 2 (line 1 column 3) at JSON.parse () Is there an easier way to achieve my purpose? -
Forbidden (CSRF cookie not set) with cookie being sent from react axios to django backend
Building simple user authentication with React and Django but have only got register coded so far. I have tried getting this to work for hours and am getting very frustrated.The react side is built and the register page is being run from the django port 8000. The development server is getting the cookie and setting it perfectly on local host port 8000. I put it in a hidden input field in my register form, then retrieve the cookie using js-cookie perfectly in auth.js (I can see this with console.log). I then send it with axios with the cookie in the header with withCredentials=true. I get the following error: error Forbidden (CSRF cookie not set.): /accounts/register [28/Feb/2024 19:39:57] "POST /accounts/register HTTP/1.1" 403 2869 I have tried various other methods of sending the cookie. I have all the relevant CORS settings set. views.py @method_decorator(ensure_csrf_cookie, name='dispatch') class GetCSRFToken(APIView): permission_classes = (permissions.AllowAny, ) def get(self, request, format=None): return Response({ 'success': 'CSRF cookie set'}) auth.js import axios from 'axios'; import { REGISTER_SUCCESS, REGISTER_FAIL } from './types'; import Cookies from 'js-cookie' export const register = (username, password, re_password) => async dispatch => { const config = { withCredentials: true, headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'X-CSRFToken': … -
Django Summernote not rendering <font> tag with safe filter
when I try to change the 'color' in Summernote, Django doesn't render it properly; it gives the HTML tag instead of the color change. In the Django admin, it works well. <font color="#000000" style="background-color: rgb(255, 255, 0);">TEXT</font> The other attributes work fine. SUMMERNOTE_CONFIG = { 'iframe': True, 'summernote': { 'airMode': False, 'height': '291', 'width': '100%', 'toolbar': [ ['style', ['style']], ['font', ['bold', 'underline', 'clear']], ['fontname', ['fontname']], ['color', ['color']], ['para', ['ul', 'ol', 'paragraph']], ['table', ['table']], ['insert', ['link', 'picture', 'video']], ['view', ['fullscreen', 'codeview', 'help']], ], } } in the html <div class="content"> <p>{{ question.body|safe }}</p> </div> Can someone give me a hint for this? Ty a lot!!!!! -
how to proper setup ALLOWED_HOST to allow other machine in the network access the web
Django server in machine TestPC-A , at 192.25.56.120 I want it accessible from the computer in the same network 192.25.56.xxx. what I have configured 1. settings.py ALLOWED_HOSTS = ["127.0.0.1", "localhost", "TestPC-A" , "0.0.0.0", "192.25.56.120"] 2. runserver.bat @echo off REM Activate virtual environment in the current terminal session and run server cmd /k ".venv\Scripts\activate && python manage.py runserver_plus --cert-file cert.pem --key-file key.pem 0.0.0.0:8000" I have tried to add following in Windows hosts file C:\Windows\System32\drivers\etc\hosts 192.25.56.120 TestPC-A I restart the server, and the web page is not loaded at another computer's web browser https://TestPC-A:8000/ What else that I need to set? -
Importing CSV ManyToManyField into Django model with Pandas
I'm very new to Django and trying to write a small service app for work. Mostly everything is working so far except I cannot seem to get my csv to import with the M2M fields. I now know that you can't directly import to an M2M field, but I can't seem to get it working. My models.py class Service_Interval(models.Model): interval_name = models.CharField(null=True, max_length=200, help_text='Enter the name of the service interval') class Task(models.Model): service_intervals = models.ManyToManyField(Service_Interval, help_text="Select a Service Interval") My views.py: df=pd.read_csv(filename, sep=',', usecols=['Requirements','Service Interval','Task Current', 'Task Created','Task Name', 'Task Number']) #print(df) row_iter = df.iterrows() objs = [ Task( #id = row['ID'], requirements = row['Requirements'], #service_intervals = row['Service Interval'], <- wont import service_intervals = Service_Interval.interval_name.set(interval_name=row['Service Interval']) task_created = row['Task Created'], task_current = row['Task Current'], task_name = row['Task Name'], task_number = row['Task Number'], ) for index, row in row_iter ] Task.objects.bulk_create(objs) I cannot seem to get this working or find a solution to fit in with iteration? service_intervals should add the interval name to Service_Interval.interval_name. I cannot seem to retrofit any researched solutions. Everything else imports fine. Any help would be appreciated. -
Optimizing Django View to Handle Large Data Sets Efficiently
I'm seeking advice on optimizing a Django view to enhance its performance, particularly when dealing with a large number of clients in the database. Here's the scenario: I have a Django view called tClients that retrieves client data and renders it on a webpage. The view performs filtering based on a query parameter called status. If status is provided and falls within certain values, the view filters clients accordingly. Here's the current implementation of the view: @login_required(login_url='/accounts/login') def tClients(request): client_Form = NewClient() client_update_form = ClientUpdateForm() filter_status = request.GET.get('status', None) if filter_status is not None and filter_status in ['-1', '0', '1']: clients = Client.objects.select_related() # values('id','nni','nom','date','telephone','address','observation') clients = [client for client in clients if client.is_debt == int(filter_status)] else: clients = Client.objects.values('id','nni','nom','date','telephone','address','observation') context = { 'client_Form': client_Form, 'client_update_form': client_update_form, 'tClients': clients, } return render(request, 'clients/list_clients.html', context) The Client model is defined as follows: class Client(models.Model): nni = models.CharField(max_length=20, verbose_name=_('nni'), unique=True) uid = models.CharField(max_length=500) nom = models.CharField(max_length=255, verbose_name=_('nom')) date = models.DateField(verbose_name=_("date d'inscription")) img = models.ImageField(upload_to='client/qrcodes', blank=True, null=True, verbose_name=_("Image")) telephone = models.CharField(max_length=255, null=True, verbose_name=_("Telephone")) address = models.CharField(null=True, max_length=255, verbose_name=_("Address")) observation = models.TextField(null=True, verbose_name=_("Observation")) user = models.ForeignKey(User, blank=True, on_delete=models.SET_NULL, null=True) @property def is_debt(self): current_date = timezone.localdate() debts = self.client_detter.all() if debts.exists(): for debt in debts: … -
What is Django ORM equivalent for sql "field <> 1"?
Assuming that "field" is nullable, in raw sql condition WHERE field <> 1 will exclude all non 1 rows and also exclude all NULL rows. Why Django ~Q(field=1) makes query WHERE (NOT (field = 1 AND field IS NOT NULL)) which results to include NULL rows. Is there equivalent for sql field <> 1 in Django ORM? -
Project Django does not recognize field
So. I'm creating a login page app. I have a registration page where you can add username, email and password, then you need to confirm your email through a code that's send into your email everything works well, including sending the email, but confirming the user code with the template input is giving me problems first of all, I'll show my views (won't waste time with model because it's a simple user model, with a boolean field called is_email_confirmed with default = False) views.py def createuser(request): form = MyUserCreationForm() confirmed = User.is_email_confirmed if request.method == 'POST': form = MyUserCreationForm(request.POST) if form.is_valid(): code = User.objects.make_random_password(length=6,allowed_chars='1234567890') user = form.save(commit=False) user.is_active = False user.save() user.code = code usercode = user.code user.save() subject = 'Confirm your email' confirmation_code = code message = f'Confirm your email with this code: {confirmation_code}' from_email = 'adryanftaborda@gmail.com' to_email = user.email send_mail(subject,message,from_email,[to_email]) input_code = request.POST.get('verify_code') # NOT WORKING if input_code == usercode: confirmed = User.is_email_confirmed == True if confirmed: user.is_active = True user.save() return redirect('home') else: messages.error(request,'Wrong code.') else: messages.error(request,'An error occured during your registration') context = {'form':form} return render(request, 'signup.html', context) as I said, everything seems to work, until here: input_code = request.POST.get('verify_code') # NOT WORKING if input_code == … -
How can I deal with tom-select and django form?
I found recently tom-select as alternative to Select2 for my forms. It's a great solution who work perfectly ! It works great when I use to create data from a form but when I want to use to edit data it's another problem. My edition form is in a modal ad this modal is opened by clicking on edit button on an item listing on main page behind. I use fetch in javascript to get data and to populate my input/select. It works well when I first open my modal ... but if I click on another item to edit next ... no clear data ... and error message in console saying there is allready an instance of tom-select for this input. My goal is to retrieve data (sometime it's a single select, sometime it's a multiple select) on tom-select with an easy part as I did with Select2. Here is my form <div class="modal fade">[...] <form id="product-form" method="post" action="{% url 'products' %}" class="mt-2"> {% csrf_token %} {% include 'form.html' with form=form %} <input type="hidden" name="id_product" id="id_product" value="" /> <div class="d-flex gap-2"> <a href="#" type="button" class="btn btn-secondary col-3" data-bs-dismiss="modal">{% trans 'Retour' %}</a> <button id="btn-product-modal" type="submit" class="btn btn-success col-9">{% trans 'Créer' … -
'ProgrammingError: cannot cast type bigint to uuid' in Django
I've been moving development of my website over to using Docker. I replaced sqlite as my database with postgresql then ran the command docker-compose exec web python manage.py migrate in my Docker environment and it produced the following error: File "/usr/local/lib/python3.11/site-packages/django/db/backends/utils.py", line 87, in _execute return self.cursor.execute(sql) ^^^^^^^^^^^^^^^^^^^^^^^^ psycopg2.errors.CannotCoerce: cannot cast type bigint to uuid LINE 1: ...quirementschat" ALTER COLUMN "id" TYPE uuid USING "id"::uuid ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/code/manage.py", line 22, in <module> main() File "/code/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.11/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.11/site-packages/django/core/management/__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.11/site-packages/django/core/management/base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.11/site-packages/django/core/management/base.py", line 458, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/core/management/base.py", line 106, in wrapper res = handle_func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/core/management/commands/migrate.py", line 356, in handle post_migrate_state = executor.migrate( ^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/db/migrations/executor.py", line 135, in migrate state = self._migrate_all_forwards( ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/db/migrations/executor.py", line 167, in _migrate_all_forwards state = self.apply_migration( ^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/db/migrations/executor.py", line 252, in apply_migration state = migration.apply(state, schema_editor) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/db/migrations/migration.py", line 132, in apply operation.database_forwards( File "/usr/local/lib/python3.11/site-packages/django/db/migrations/operations/fields.py", line 235, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File "/usr/local/lib/python3.11/site-packages/django/db/backends/base/schema.py", line …