Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
FormData file upload to Django model?
I'm trying to upload a file through a jQuery ajax request, using FormData. When I set processData and contentType to false, I get the error Forbidden (CSRF token missing.). When I remove those, I get the error Uncaught TypeError: 'slice' called on an object that does not implement interface Blob.. What am I missing here? $(".form").on("submit", function(event) { event.preventDefault(); $.ajax({ url: "/upload_profile_pic/", type: "POST", data: { "profile_pic": formData.get("file"), "csrfmiddlewaretoken": $(this).find("input[name='csrfmiddlewaretoken']").val() }, }, success: function (data) { console.log("success: "+data); }, error: function (data) { console.log(data); } }); }); -
Django vs PHP 8.*: Memory usage with 1000 concurrent visitors
I'm currently deciding between Django (Python) and PHP 8.* for a very large project that expects high traffic. Memory usage is a crucial factor for me since the website will need to handle a significant number of concurrent visitors. For example, let's say the site needs to handle 1000 concurrent visitors. Please consider that the project will be well optimized. From what I understand: PHP creates a new process for each request, which might lead to higher memory consumption under heavy load since each request is handled separately. Django, on the other hand, uses a persistent process to handle requests, which might help with better memory management but could also cause its own memory-related concerns under high traffic. I've asked ChatGPT for advice on this, but it gives random and wrong answers, so I don't trust it. I'm looking for insights or benchmarks that compare the memory usage of PHP and Django when handling high traffic and concurrent users. Specifically, how much memory each might use when handling around 1000 concurrent visitors, and any research on how each stacks up in terms of scalability and memory efficiency. Which language/framework would you recommend if memory usage is a key factor for … -
Arrows in Maplibre
Hey I am using maplibre for custom map, i am using geodjango for backend, data coming from database is { id: "arrow_tile_layer", type: "symbol", source: "arrow", 'source-layer': "line", minzoom: 16, maxzoom: 20, filter: ["==", ["get", "way_type"], "primary"], paint: {'text-color': '#000000', 'text-opacity': 0.8}, layout: {'text-font': ['Noto Sans Regular'], 'text-size': 12, 'text-field': '- > ', 'symbol-placement': 'line'}, } there isn't any error in the frontend however, in the map arrows is not visible I have tried to show the arrows in highway, but it is not visible -
"Token contained no recognizable user identification" when refreshing access token
i have the following setup for logging user in and giving out the access and refresh token, refresh token is set in cookies and the access_token is just handed out in json # login_views class UserLoginAPIView(APIView): class UserLoginInputSerializer(serializers.Serializer): username_or_email = serializers.CharField(write_only=True) password = serializers.CharField(write_only=True) class UserLoginOutputSerializer(serializers.Serializer): username = serializers.CharField(read_only=True) user_email = serializers.EmailField(read_only=True) full_name = serializers.CharField(read_only=True) is_verified = serializers.BooleanField(read_only=True) verification_required = serializers.BooleanField(read_only=True) user_type = serializers.ListField(child=serializers.CharField(), read_only=True) staff = serializers.BooleanField(read_only=True) superuser = serializers.BooleanField(read_only=True) access_token = serializers.CharField(read_only=True) def post(self, request, *args, **kwargs): input_serializer = self.UserLoginInputSerializer(data=request.data) input_serializer.is_valid(raise_exception=True) try: login_details, refresh_token = user_login( **input_serializer.validated_data ) except DjangoValidationError as e: return Response( { "success": False, "message": e.message, }, status=status.HTTP_401_UNAUTHORIZED, ) except ValidationError as e: return Response( { "success": False, "message": e.detail[0], }, status=status.HTTP_401_UNAUTHORIZED, ) except Exception as e: return Response( { "success": False, "message": str(e), }, status=status.HTTP_400_BAD_REQUEST, ) output_serializer = self.UserLoginOutputSerializer(login_details) response = Response( { "success": True, "message": "User log in successful.", "data": output_serializer.data, }, status=status.HTTP_200_OK, ) response.set_cookie( "refresh_token", refresh_token, max_age=settings.REFRESH_COOKIE_MAX_AGE, httponly=True, samesite="none", secure=False, ) return response def user_login(*, username_or_email: str, password: str) -> tuple: """ Verifies user's credentials & returns access token & refresh token. """ @dataclass(frozen=True) class UserLoginDetails: user_type: List[str] username: str user_email: str full_name: str is_verified: bool access_token: str staff: bool superuser: bool … -
Struggling with Vitess MySQL Integration: Issue
I’m working with Vitess on my server and trying to integrate it with a simple demo Django project using the Vitess MySQL databases. I’ve already set up Vitess using Docker and have successfully logged into MySQL within the Vitess container, and for the container, I used to create a subnet so the container has a separate IP. However, I’m running into an issue when trying to connect to a vitess MySQL server from outside container; even on the same server, it will not connect, showing error only -> step 1: Connect the vitess mysql server from outside container with the same server. ERROR IMAGE: enter image description here -> In that command , i use to connect host as container IP because I am trying to connect vitess MYSQL server from outside the container If I use localhost it will not connect inside container, localhost working fine inside the container but outside we must pointing the container IP then only it connect from outside. -> Step 2: Connectiong or migrating from Django application ERROR IMAGE: enter image description here -> in this django application tring to migrate the data to vitess mysql server it will show this error i tring … -
Shared hosting on Django
How to host a Django project on shared hosting? I have Python version: 3.12.8,Shared Hosting Provider: Hostinger, Web server available:Nginx and Database: SQLite.How to set up the database for Django on shared hosting and how to configure Apache or Nginx to work with Django on shared hosting. How to set up static files and media files correctly for production. -
Docker. How to fill volume at startup
I use docker-compose to run a Django project. My goal is for docker to start filled with existing data (statics, database, and all the contents of the media directory). Currently, statics are collected and distributed via volume. The database starts from a prepared dump. /media directory added to .dockerignore The question is, how to correctly fill the media volume from the media directory when you first run docker compose (that is, when the media volume is still empty)? docker-compose.yaml file: volumes: mysql_data: static: media: services: db: image: mysql:8.0 restart: always volumes: - mysql_data:/var/lib/mysql - ./database_dump.sql:/docker-entrypoint-initdb.d/dump.sql environment: - MYSQL_DATABASE=${MYSQL_DATABASE} - MYSQL_USER=${MYSQL_USER} - MYSQL_PASSWORD=${MYSQL_PASSWORD} - MYSQL_ROOT_PASSWORD=${MYSQL_ROOT_PASSWORD} env_file: - .env backend: build: ./ depends_on: - db restart: always volumes: - static:/app/static/ - media:/app/media/ env_file: - .env nginx: build: ./gateway/ depends_on: - backend ports: - "8000:80" restart: always volumes: - static:/static/ - media:/media/ Dockerfile: FROM python:3.11 WORKDIR /app ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 ENV DJANGO_SETTINGS_MODULE='app.settings' RUN apt-get update && apt-get install -y netcat-openbsd COPY ./requirements.pip ./ RUN pip install --upgrade pip && pip install -r requirements.pip --no-cache-dir COPY . . RUN python manage.py collectstatic --no-input RUN chmod +x ./entrypoint.sh EXPOSE 8000 ENTRYPOINT ["./entrypoint.sh"] entrypoint.sh: #!/bin/sh echo "Waiting for MySQL..." while ! nc -z $MYSQL_HOST $MYSQL_PORT; … -
What's the correct way to use transaction.on_commit with Celery tasks in Django?
Approach 1: Without transaction.atomic Source: https://adamj.eu/tech/2022/08/22/use-partial-with-djangos-transaction-on-commit/ def order_created(order): order.status = 'created' order.save() transaction.on_commit( partial(send_order_email.delay, order_id=order.id) ) Approach 2: With transaction.atomic def order_created(order): with transaction.atomic(): order.status = 'created' order.save() transaction.on_commit( partial(send_order_email.delay, order_id=order.id) ) Which approach is correct and why? The save() operation makes database changes, but examples differ on whether transaction.atomic is needed. (ATOMIC_REQUESTS=False in settings) -
OSError: [Errno 24] Too many open files even after using with context manager
I've a Django application running on a server I'm using gunicorn on server this what my gunicorn service file looks like myapp.service [Unit] Description=myapp daemon Requires=myapp.socket After=network.target [Service] User=root Group=www-data WorkingDirectory=/myappApi/ ExecStart=/myappApi/venv/bin/gunicorn \ --access-logfile - \ --workers 10 \ --timeout 0 \ --bind unix:/run/myapp.sock \ myappProject.wsgi:application [Install] WantedBy=multi-user.target and this is the error I'm getting File "/myappApi/views.py", line 293, in CustomHandler Jan 23 10:48:30 myapp gunicorn[2957207]: app = CustomApp() Jan 23 10:48:30 myapp gunicorn[2957207]: File "app.py", line 22, in __init__ Jan 23 10:48:30 myapp gunicorn[2957207]: self.logger = start_logger(__file__) Jan 23 10:48:30 myapp gunicorn[2957207]: File "utils/loggerUtil.py", line 19, in start_logger Jan 23 10:48:30 myapp gunicorn[2957207]: OSError: [Errno 24] Too many open files: 'conf/config.json' above error is raised by this code from logging.handlers import RotatingFileHandler import os, logging, time, json def start_logger(__file__): os.makedirs('logs', exist_ok=True) fileName = os.path.basename(__file__) logdatetime = time.strftime("%d-%m-%Y-%I-%M") logFilename = 'logs/' + fileName[:-3] + logdatetime + '.log' logger = logging.getLogger(__file__) ''' Setting the threshold of logger to DEBUG ''' with open("conf/config.json") as f1: data = json.load(f1) # Rotating handler handler = RotatingFileHandler( logFilename, maxBytes=data['maxBytes'], backupCount=data['backupCount']) logger.addHandler(handler) return logger I've checked this answer it increases ulimit of a file which is okay but It's a temporary solution. I've noticed I'm using … -
Django: How to Represent and Query Symmetrical Relationships for a Family Tree?
I am building a family tree application in Django where I need to represent and query marriages symmetrically. Each marriage should have only one record, and the relationship should include both partners without duplicating data. Here's the relevant model structure: class Person(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) spouses = models.ManyToManyField( 'self', through="Marriage", symmetrical=True, related_name="partners" ) class Marriage(models.Model): person1 = models.ForeignKey(Person, on_delete=models.CASCADE, related_name="marriages_as_person1") person2 = models.ForeignKey(Person, on_delete=models.CASCADE, related_name="marriages_as_person2") start_date = models.DateField(null=True, blank=True) end_date = models.DateField(null=True, blank=True) I want to: Ensure both partners appear as spouses for each other symmetrically. Avoid duplicate entries for the same marriage. Efficiently query all spouses of a person. Here’s the code I’m using to query spouses: # Query spouses for a person p1 = Person.objects.create() p2 = Person.objects.create() Marriage.objects.create(person1=p1, person2=p2) p1.spouses.all() # Returns list containing p2 p2.spouses.all() # Returns empty list However, I’m facing challenges: If p1 spouses are queried, it should contain p2 and if p2 spouses are queried, it should contain p1 Both queries are not symmetrical Questions: Is my model structure correct for representing marriages symmetrically? If not, what improvements should I make? How can I efficiently query all spouses of a person in a database-optimized way while ensuring symmetry? -
Django: rest endpoint not found
I am trying to implement a rest endpoint with Django. My views.py is: from django.http import JsonResponse from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status import json from .utils import retrieve_and_detect_faces @api_view(["POST"]) def video_analysis(request): data = json.loads(request.body) timestamp = data.get("timestamp") return JsonResponse({....}) And in urls.py: from django.urls import path from .views import video_analysis urlpatterns = [ path('video_analysis/', video_analysis, name = 'video_analysis') ] But when I try to call this endpoint, I get error: Not Found: /video_analysis [24/Jan/2025 07:37:26] "POST /video_analysis?timestamp=1234567 HTTP/1.1" 404 2262 What configuration am I missing in my program? -
AllAuth.url is not working and not showing path sugestions
Setting.py: INSTALLED_APPS = [ 'channels', 'allauth', 'allauth.account', 'allauth.socialaccount', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "corsheaders", ] MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware", 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', "allauth.account.middleware.AccountMiddleware", 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ] File: url.py urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('allauth.urls')), ] Like, I just followed the quickstart of all auth, and I've done this once before with a tutorial, but this time something went wrong because when I search for : localhost:8000/accounts/ it says the path doesn't exists, instead of giving me suggestions of follow up. And when I go localhost:8000/ it does suggest admin/, accounts/ -
BadRequest can't return JSON?
I am trying to return a JSON object along with a 400 error code. This correctly returns the object (e.g. {"email": ["A user with that email address already exists."]}: return HttpResponse(json.dumps(dict(form.errors.items()))) Whereas these all just returns an unreadable (by javascript) object ([object Object]): return BadRequest(json.dumps(dict(form.errors.items()))) return HttpResponseBadRequest(json.dumps(dict(form.errors.items()))) return BadRequest(json.dumps(dict(form.errors.items())), content_type='application/json') I've tried several other methods of sending an error code but the results were the same. How do I get the readable object along with a 400 Bad Request error code? -
How to configure dynamic language switching for API responses using i18n_patterns in Django?
I am working on a Django project and need to implement multilingual support for my REST API. I want the API to return responses in the selected language based on the URL prefix (e.g., /en/, /ml/) using i18n_patterns. I’ve done the following: In settings.py, I’ve defined the available languages: LANGUAGES = [ ('en', 'English'), ('ml', 'Malayalam'), ] LANGUAGE_CODE = 'en' I’ve added 'django.middleware.locale.LocaleMiddleware' to the MIDDLEWARE setting: MIDDLEWARE = [ ... # other middlewares 'django.middleware.locale.LocaleMiddleware', ] In the project’s urls.py, I’ve used i18n_patterns to ensure the URLs are prefixed with the language code: from django.conf.urls.i18n import i18n_patterns urlpatterns = [ path('admin/', admin.site.urls), path('auth/', include('accounts.urls')), path('app/', include('app.urls')) ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns = i18n_patterns(*urlpatterns) The Issue: While I can specify the language via the URL (e.g., /ml/ for Malayalam), the API responses are not being automatically translated to the selected language. The responses remain in English even when the Accept-Language header or language prefix is set to another language (e.g., Malayalam) What I Expect: I expect the API responses to be auto-translated into the selected language (e.g., Malayalam) based on the URL prefix or Accept-Language header. What I Have Tried: I’ve confirmed that LocaleMiddleware is active in MIDDLEWARE. I’ve ensured that … -
How to display video of cloudnary in admin panel and play
So, I am using cloudinary in django for video handling. video handling is going very well but i want to display video on admin panel. models.py course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name='Course') public_id = models.CharField(max_length=130, blank=True, null=True) title = models.CharField(max_length=120) description = models.TextField(max_length=500, blank=True, null=True) thumbanil = CloudinaryField( "image", blank=True, null=True, public_id_prefix=get_public_id_prefix, display_name=get_display_name, tags=get_tags ) video = CloudinaryField( "video", blank=True, null=True, type='private', resource_type="video", public_id_prefix=get_public_id_prefix, display_name=get_display_name, tags=get_tags ) admins.py import helpers from cloudinary import CloudinaryImage from django.contrib import admin from .models import Course, Lesson from django.utils.html import format_html class LessonInline(admin.StackedInline): model = Lesson fields = ['public_id', 'title', 'description', 'thumbanil', 'display_thumbnail' , 'video', 'display_video_content', 'order', 'can_preview', 'status', 'updated', 'timestamp'] readonly_fields = ['public_id', 'updated', 'timestamp', 'display_thumbnail', 'display_video_content'] extra = 0 # means number of empty forms display in admin panel for adding lessons ok. def display_video_content(self, obj): url = helpers.get_cloudinary_video_object( obj, field_name="video", as_html=False, width=400, height=350, sign_url=False, fetch_format="auto", quality="auto" ) return format_html(f"<source src='{url}' type='video/mp4' /sourse>") display_video_content.short_description = 'Current Video' helper/server.py def get_cloudinary_video_object( instance, field_name="video", as_html=False, width=None, height=None, sign_url=False, # for private videos fetch_format="auto", quality="auto" ): if not hasattr(instance, field_name): return "" video_objest = getattr(instance, field_name) # give the value of instance fielsname if match with inatance if not video_objest: return "" video_options = { "sign_url": … -
apache2 not runing django error ImportError: No module named site
sudo vi /etc/httpd/conf.d/canon.conf <VirtualHost *:80> ServerAdmin webmaster@localhost ServerName your_domain_or_ip # Path to the root of your Django app DocumentRoot /home/ec2-user/erp-edi-integration/canon # Update to the new virtual environment path WSGIDaemonProcess canon python-home=/home/virtual-env/venv WSGIProcessGroup canon WSGIScriptAlias / /home/ec2-user/erp-edi-integration/canon/canon/wsgi.py # Set up static files Alias /static/ /home/ec2-user/erp-edi-integration/canon/static/ <Directory /home/ec2-user/erp-edi-integration/canon/static> Require all granted </Directory> # Set up media files Alias /media/ /home/ec2-user/erp-edi-integration/canon/media/ <Directory /home/ec2-user/erp-edi-integration/canon/media> Require all granted </Directory> <Directory /home/ec2-user/erp-edi-integration/canon/canon> <Files wsgi.py> Require all granted </Files> </Directory> canon/wsgi.py import os, sys sys.path.insert(0, '/home/ec2-user/erp-edi-integration/canon') sys.path.insert(0, '/home/virtual-env/venv/lib/python3.9/site-packages') sys.path.insert(0, '/home/virtual-env/venv/lib/python3.9/lib-dynload') os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'canon.settings') from django.core.wsgi import get_wsgi_application application = get_wsgi_application() >>> import sys >>> print(sys.path) ['', '/home/ec2-user/miniconda3/envs/myenv/lib/python39.zip', '/home/ec2-user/miniconda3/envs/myenv/lib/python3.9', '/home/ec2-user/miniconda3/envs/myenv/lib/python3.9/lib-dynload', '/home/virtual-env/venv/lib/python3.9/site-packages'] all requirement already install check virtual environment source /home/virtual-env/venv/bin/activate # Activate again after all this when i run my server restart then in apache log error show me this ImportError: No module named site what is wrong in this my project path is /home/ec2-user/erp-edi-integration/canon/canon/wsgi.py -
I want to make a dropdown item send data to a form, help needed
I have this dropdown that fills itself with the make of cars inside my database and i want to make each one of the items(when selected) send their name to a dorm (ex: if i press Fiat i want the item to send the name Fiat to the form). I would appreciate any help :) Also if you saw a post with a similar question let me know, thanks :) Here is the code i got: {% extends "layout.html" %} {% block content %} {% load static %} <link rel="stylesheet" href="{% static 'css/styles.css' %}?v=1"> <!-- search bar for advanced search--> <div class="container-search"> <br> <h1 class="text-center text-white">Search Cars</h1> <hr> <form method="get" action="{% url 'search' %}"> <!-- Dropdowns - Side by side --> <div class="d-flex justify-content-center mb-3"> <div class="dropdown me-3"> <button class="btn btn-danger dropdown-toggle" type="button" id="makeDropdown" data-bs-toggle="dropdown" aria-expanded="false"> Select Make </button> <ul class="dropdown-menu" aria-labelledby="makeDropdown"> {% for make in car_makes %} <post value="{{make.make}}" name="{{ make.make }}" class="text-dark">{{ make.make }}</post> <br> {% endfor %} </ul> </div> <div class="dropdown"> <button class="btn btn-danger dropdown-toggle" type="button" id="modelDropdown" data-bs-toggle="dropdown" aria-expanded="false"> Select Model </button> <ul class="dropdown-menu" aria-labelledby="modelDropdown"> {% if cars != None %} {% for car in cars %} <option value="{{ car.model }}" class="text-dark">{{ car.model }}</option> {% endfor %} … -
Custom generic istruthy/isfalsy lookup doesn't work on Foreign Keys
In my Django project, I'm in need of a generic istruthy/isfalsy lookup that would work on any type of database field. Example of models.py: class MyModel(models.Model): my_charfield = models.CharField(...) my_decimalfield = models.DecimalField(...) my_datefield = models.DateField(...) my_boolfield = models.BooleanField(...) my_fkfield = models.ForeignKey(...) What I want to be able to do: MyModel.objects.filter(my_charfield__isfalsy=True) MyModel.objects.filter(my_decimalfield__isfalsy=True) MyModel.objects.filter(my_datefield__isfalsy=True) MyModel.objects.filter(my_boolfield__isfalsy=True) MyModel.objects.filter(my_fkfield__isfalsy=True) I have defined two custom lookups to do that: from django.db.models import Lookup, BooleanField, ForeignKey, Field class IsTruthy(Lookup): lookup_name = 'istruthy' def as_sql(self, compiler, connection): lhs, params = self.process_lhs(compiler, connection) if isinstance(self.lhs.output_field, BooleanField): return f"{lhs} = TRUE", params if isinstance(self.lhs.output_field, ForeignKey): lhs = f"{lhs}_id" return f"{lhs} IS NOT NULL", params return f"{lhs} IS NOT NULL AND {lhs} <> ''", params class IsFalsy(Lookup): lookup_name = 'isfalsy' def as_sql(self, compiler, connection): lhs, params = self.process_lhs(compiler, connection) if isinstance(self.lhs.output_field, BooleanField): return f"{lhs} = FALSE", params if isinstance(self.lhs.output_field, ForeignKey): lhs = f"{lhs}_id" return f"{lhs} IS NULL", params return f"{lhs} IS NULL OR {lhs} = ''", params Field.register_lookup(IsTruthy) Field.register_lookup(IsFalsy) These custom lookups work on all fields except ForeignKey. When used on a ForeignKey, the following error is triggered: django.core.exceptions.FieldError: Unsupported lookup 'isfalsy' for ForeignKey or join on the field not permitted I have tried different variations of this code to handle … -
Temporarily load a fixture for development
I would like to create a lot of dummy products for use in development. The dummy products need to be in the development database, in addition to a copy of all of the data that the production database has, so that I can see what the dummy products will look like in the website. How can I do this easily? I've looked into fixtures, but I can't figure out how to "apply" a fixture on top of a copy of the production database, and how I might be able to unapply it when I'm done with that part of development. -
Is this djoser implementation secure?
This question may be too broad for StackOverflow, but I'm not sure where else to go for help. I wrote a simple authentication system in Django with Djoser and its JWT implementation, using jQuery on the frontend. I really don't know what I'm doing though, and I'm about 99% sure I did it wrong and it's totally insecure. First, when a user submits the login form, I send a POST request to retrieve a refresh token and an access token. The refresh token is stored as a cookie, and the access token is stored in sessionStorage: // Post the form $.post("/auth/jwt/create/", $(this).serialize()) // Success: store tokens & redirect .done(function(data) { // Logged in: set redirect path & store tokens if (data.refresh !== "undefined" && data.access !== "undefined") { Cookies.set("refresh_token", data.refresh, { expires: 30, secure: true, sameSite: "strict" }); sessionStorage.setItem("access_token", data.access); } }) I have another simple script that runs every time a page is loaded. There, I verify the access token, attempt a refresh if it's invalid, fetch user data using the access token, then post that user data to the backend to login. This script also logs the user out if on the logout page: // Log in or … -
Data not saved to database
I don't know what's going on here, whenever I try to create a buzz with the status set to Draft (this is also the default status set on the model) Django returns a 302 response and does not saved it to the database. However, when I change the status to Published it just saves it normally on the database. Here's the code to the view def buzz_create(request): form = BuzzCreateForm() if request.method == 'POST': form = BuzzCreateForm(data=request.POST) if form.is_valid: buzz = form.save(commit=False) buzz.author = request.user buzz.save() return redirect(to=reverse('buzz:buzz_list')) return render( request=request, template_name='buzz/create.html', context={ 'form': form } ) Here's the code to the model: class BuzzPublishedManager(models.Manager): def get_queryset(self): return ( super().get_queryset().filter(status=Buzz.Status.PUBLISHED) ) class Buzz(models.Model): class Status(models.TextChoices): PUBLISHED = 'PBL', 'Published' DRAFT = 'DFT', 'Draft' title = models.CharField(max_length=250) body = models.TextField() slug = models.SlugField(max_length=250, unique_for_date='publish') publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) author = models.ForeignKey( to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='buzzes' ) status = models.CharField( max_length=3, choices=Status, default=Status.DRAFT ) published = BuzzPublishedManager() objects = models.Manager() class Meta: verbose_name_plural = 'Buzzes' ordering = ['-publish'] indexes = [ models.Index(fields=['-publish']) ] def __str__(self): return self.title The objects in the model was not there before. I tried adding it maybe the data is saved but not queried … -
Django Allauth's Google Login Redirect and Page Design
Currently, on the login page, I have a button: <div class="d-grid gap-2"> <a href="{% provider_login_url 'google' %}" class="btn btn-danger"> <i class="fab fa-google"></i> Sign in with Google </a> </div> This redirects to accounts/google/login/, and that page allows for redirection to Google authentication. I have two problems: I don't know if these two steps are necessary and I don't see the value of having the extra step accounts/google/login/. I don't know how to replace the standard layout of the accounts/google/login/ page (in case it is really needed). -
Access request session data of DetailView in CreateView in django
I am writing a library management system in Django. There are two views that I am having a bit of a struggle. The BookDetailsView lists the details of a Book such as title, price, etc. class BookDetailsView(LoginRequiredMixin, DetailView): model = Book template_name = 'book_detail.html' def get(self, request, *args, **kwargs): response = super().get(request, *args, **kwargs) request.session['book_pk'] = kwargs['pk'] return response # used to mark book as read or unread def post(self, request, *args, **kwargs): if 'is_read' in request.POST: book = Book.objects.get(pk=kwargs['pk']) book.is_read = True book.save() return HttpResponseRedirect(self.request.path_info) In the BookBorrowView, I display a form where the reader can borrow a book. Two fields are preset (borrowers and book), and I don't want the user to be able to change them. At the moment, the user can select among many options. class BookBorrowView(LoginRequiredMixin, CreateView): model = BookBorrowTransaction template_name = 'book_borrow.html' fields = ['book', 'borrowers', 'date_borrowed', 'to_return', ] success_url = reverse_lazy('home') def get_initial(self): initial = super(BookBorrowView, self).get_initial() initial['borrowers'] = get_object_or_404(CustomUser, email=self.request.user.email) initial['book'] = get_object_or_404(Book, title=Book.objects.get(pk=self.request.session['book_pk']).title) # need the book id here print(self.request.GET) print(self.request.POST) print(self.request.session['book_pk']) return initial The following is a screenshot of the form displayed by the BookBorrowView. I have two questions: I am passing the primary key for the book through request.session … -
Export command not found in working django import-export app
I'm trying to reproduce the export command as shown in the import-export docu python manage.py export CSV auth.User yet all I get is: Unknown command: 'export'. Type 'manage.py help' for usage. Besides the management command, the import-export api works fine -
Django: Unable to login into a account
I have created a custom user model in my django model where the password is being saved using make_password from password_strength but when trying to login using the check_password it says invalid username or password. @csrf_exempt def login_attempt(request): if request.method == 'POST': try: data = json.loads(request.body) email = data.get('email') password = data.get('password') try: user_obj = user.objects.get(email=email) except user.DoesNotExist: return JsonResponse({'success': False, 'message': "Email doesnot exists"}, status=401) if check_password(password, user_obj.password): login(request, user_obj) return JsonResponse({'success': True, 'message': "Login successful"}, status=200) else: return JsonResponse({'success': False, 'message': "Invalid email or password"}, status=401) except Exception as e: return JsonResponse({'success': False, 'message': f"Error: {str(e)}"}, status=500) return JsonResponse({'success': False, 'message': "Invalid request method"}, status=405)