Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Testing Django user and group permissions with a simple test fails
I've created a simple test with Django for testing permissions on class Reminder. ... class ReminderPermissionsTestCase(TestCase): def setUp(self): call_command('migrate') # Create content type for Reminder model content_type = ContentType.objects.get_for_model(Reminder) # Create permissions for Reminder model add_perm = Permission.objects.create( codename="add_reminder", name="Can add reminder", content_type=content_type ) view_perm = Permission.objects.create( codename="view_reminder", name="Can view reminder", content_type=content_type ) change_perm = Permission.objects.create( codename="change_reminder", name="Can change reminder", content_type=content_type ) delete_perm = Permission.objects.create( codename="delete_reminder", name="Can delete reminder", content_type=content_type ) # Create a Location location = Location.objects.create( name="Test Location", location_number="LOC-001", slug="test-location" ) # Create a Project associated with the Location project = Project.objects.create( date_last_budget_calculate="2023-09-03 12:00:00", slug="test-project", location=location ) # Create user groups editor_group = Group.objects.create(name=f"{project.slug}-editor") user_group = Group.objects.create(name=f"{project.slug}-user") # Create users and assign them to groups editor_user = get_user_model().objects.create(username="editor_user") editor_user.groups.add(editor_group) user_user = get_user_model().objects.create(username="user_user") user_user.groups.add(user_group) # Create a Reminder with CRUD permissions reminder_crud = Reminder.objects.create( open=True, reminder_date="2023-09-03 12:00:00", subject="Reminder with CRUD permissions", project=project, created_by=editor_user, reminder_text="This is a reminder with CRUD permissions." ) assign_perm("change_reminder", editor_user, reminder_crud) assign_perm("delete_reminder", editor_user, reminder_crud) # Create a Reminder with READ permissions reminder_read = Reminder.objects.create( open=True, reminder_date="2023-09-04 12:00:00", subject="Reminder with READ permissions", project=project, created_by=editor_user, reminder_text="This is a reminder with READ permissions." ) assign_perm("view_reminder", editor_user, reminder_read) def test_editor_has_crud_permissions(self): editor_user = get_user_model().objects.get(username="editor_user") reminder_crud = Reminder.objects.get(subject="Reminder with CRUD permissions") # … -
I installed 'mysqlclient' with pipenv but python doesn't recegnize it and gives "Did you install mysqlclient" error
I installed mysqlclient inside my python virtual enviorment to connect to a mysql database. But when I change the settings.py database engine settings from sqllite to mysql: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': BASE_DIR / 'db.sqlite3', } } I get this weird error telling me I havn't installed 'mysqlclient' package Exception in thread django-main-thread: Traceback (most recent call last): File "/home/reza/.local/share/virtualenvs/store-api-wAMLFNlP/lib/python3.10/site-packages/django/db/backends/mysql/base.py", line 15, in <module> import MySQLdb as Database File "/home/reza/.local/share/virtualenvs/store-api-wAMLFNlP/lib/python3.10/site-packages/MySQLdb/__init__.py", line 17, in <module> from . import _mysql ImportError: libmysqlclient.so.21: cannot open shared object file: No such file or directory The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/lib/python3.10/threading.py", line 1016, in _bootstrap_inner self.run() File "/usr/lib/python3.10/threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "/home/reza/.local/share/virtualenvs/store-api-wAMLFNlP/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/reza/.local/share/virtualenvs/store-api-wAMLFNlP/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "/home/reza/.local/share/virtualenvs/store-api-wAMLFNlP/lib/python3.10/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/home/reza/.local/share/virtualenvs/store-api-wAMLFNlP/lib/python3.10/site-packages/django/core/management/__init__.py", line 394, in execute autoreload.check_errors(django.setup)() File "/home/reza/.local/share/virtualenvs/store-api-wAMLFNlP/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/reza/.local/share/virtualenvs/store-api-wAMLFNlP/lib/python3.10/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/reza/.local/share/virtualenvs/store-api-wAMLFNlP/lib/python3.10/site-packages/django/apps/registry.py", line 116, in populate app_config.import_models() File "/home/reza/.local/share/virtualenvs/store-api-wAMLFNlP/lib/python3.10/site-packages/django/apps/config.py", line 269, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, … -
mongoDB django _id field instead of id using djongo
trying to learn Django and decided to go with MongoDB and djongo as the connector now, when I insert a document for mongoDB it is automatically received the _id which is ObjectId from mongodb I want that when I query all items to get also this _id and I want that when I insert it will not generate the "id" field because I have already the _id, and one more thing when I get one item by id or make a put/delete request I want to check if the id on params is equals to this ObjectId so this is what I've tried on serialzer.py from rest_framework import serializers from .models import Drink class DrinkSerialzer(serializers.ModelSerializer): class Meta: model = Drink fields = ['_id','name', 'desc'] model.py from djongo import models class Drink(models.Model): _id = models.ObjectIdField() name = models.CharField(max_length=200) desc = models.CharField(max_length=500) and on the requests for example get one by id from bson import ObjectId @api_view(['GET', 'PUT', 'DELETE']) def drink_detail(request, id): try: drink = Drink.objects.get(_id=ObjectId(id)) except Drink.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = DrinkSerialzer(drink) return Response(serializer.data) It is not working, with a lot of errors for example on model: the _id cannot be null on the request it is … -
I was creating a database for a Django project I'm working on and I ran into some errors in MySQL
I am currently following freeCodeCamp's tutorial on Django but I ran into errors. I typed "python mydb.py" in my Git Bash here's the error that occured. $ python mydb.py Traceback (most recent call last): File "C:\dcrm\dcrm\mydb.py", line 10, in <module> dataBase = mysql.connector.connect( ^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\dcrm\virt\Lib\site-packages\mysql\connector\__init__.py", line 179, in connect return MySQLConnection(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\dcrm\virt\Lib\site-packages\mysql\connector\connection.py", line 95, in __init__ self.connect(**kwargs) File "C:\dcrm\virt\Lib\site-packages\mysql\connector\abstracts.py", line 716, in connect self._open_connection() File "C:\dcrm\virt\Lib\site-packages\mysql\connector\connection.py", line 208, in _open_connection self._do_auth(self._user, self._password, File "C:\dcrm\virt\Lib\site-packages\mysql\connector\connection.py", line 137, in _do_auth packet = self._protocol.make_auth( ^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\dcrm\virt\Lib\site-packages\mysql\connector\protocol.py", line 99, in make_auth packet += self._auth_response(client_flags, username, password, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\dcrm\virt\Lib\site-packages\mysql\connector\protocol.py", line 58, in _auth_response auth = get_auth_plugin(auth_plugin)( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\dcrm\virt\Lib\site-packages\mysql\connector\authentication.py", line 190, in get_auth_plugin raise errors.NotSupportedError( mysql.connector.errors.NotSupportedError: Authentication plugin 'caching_sha2_password' is not supported I am not yet good in either using Django and MySQL that's why I'm learning, can someone help me? Here is my code in my mydb.py # Install MySQL on your computer # https://dev.mysql.com/downloads/installer/ # pip install mysql # pip install mysql-connector # pip install mysql-connector-python import mysql.connector dataBase = mysql.connector.connect( host = 'localhost', user = 'root', passwd = 'cyrine18!datascience', ) # prepare a cursor object cursorObject = dataBase.cursor() # create a database cursorObject.execute("CREATE DATABASE zachyne") print("All … -
Django CMS cms_plugin setup for a message form to send an email is not working
I've setup a django cms site for a friend so that he can easily swap pictures out and do much of the work from the front-end. It's a very simple site and working great, but I have a page called 'contacts' using it's own cms template with a placeholder for the contact_form with the key component being a message form that sends the content as an email, this functionality is the reason I need to pull the form in as a plugin from the utilities app. It works great as a standalone django page, if the form is valid, it sends the email and a success message pops up as a bootstrap 5 alert advising it was sent; if the form isn't valid, an error message pops up instead. In the cms plugin however, I can add it in and it looks fine on the page but none of the functionality provided by the utilities/views/contact_form works and it doesn't appear to use the view functionality at all apart from drawing the template location from it. I've tested this with including print() at a few places in the utilities/views.py file. Any advice on how to ensure the full functionality of the … -
Django annotation across multiple models
I am looking to annotate to each BonusCustomer the Sum of billable_amount from the load table. class BonusCustomer(models.Model): customer = models.CharField(max_length=150, blank=True, null=True) dispatcher = models.ForeignKey(Dispatcher, on_delete=models.DO_NOTHING, blank=True, null=True) pick_city = models.CharField(max_length=150, blank=True, null=True) class Load(models.Model): load_id = models.CharField(max_length=20, unique=True) sales_agent = models.ForeignKey(Dispatcher, on_delete=models.DO_NOTHING, to_field='name', blank=True, null=True) total_miles = models.DecimalField(max_digits=9, decimal_places=2, null=True, blank=True, editable=False) billable_amount_after_accessorial = models.DecimalField(max_digits=9, decimal_places=2, blank=True, null=True) class Dispatcher(models.Model): first_name = models.CharField(max_length=50, blank=True, null=True) last_name = models.CharField(max_length=50, blank=True, null=True) I tried bonus_customers=BonusCustomer.objects.annotate(revenue=Sum('dispatcher__load__billable_amount')) but this gives me the total load revenue for each dispatcher, not BonusCustomer. Any help is appreciated. -
Transalting from English to Chinese on Python Django
I'm trying to convert my web-app to a couple of different languages in Python Django. I have managed to do so for English and French but the problem comes in when I add the zh hans or zh-cn. I get the following error: enter image description here Here's my settings.py from pathlib import Path import cloudinary import os from django.utils.translation import gettext_lazy as _ BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'go', 'crispy_forms', 'cloudinary_storage', 'cloudinary', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'core.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'core.wsgi.application' # Database # https://docs.djangoproject.com/en/4.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, … -
CORS Error when I use django api with reactjs
I'm using ReactJS on the front end and Django API on the back end. I'm currently testing some functionality by connecting my localhost(backend) to a ngrok URL and hitting that ngrok URL with my ReactJS frontend that is already in its own test environment in PROD. The POST requests work just fine, but when there is a GET request, in the developer tools in chrome, I get the following: Access to fetch at 'https://'{NGROK URL} from origin 'https://{PROD URL}.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. I've included the necessary CORS_ALLOWED_ORIGINS and even CORS_ALLOW_ALL_ORIGINS. When I test this from frontend(localhost) to backend(localhost), it works normally. Does anyone know why this wouldn't work? -
How to Integrate WebSocket with Django API Views for Messaging
I am new to Djnago and new to WebSockets so I am a little unsure on the proper integration to use when working with messaging. I have an API view to send a message to a user which adds that message to the database and also create a websocket message. I also have an API view to get the conversation between 2 users. My logic is that when a user opens their conversation on the front-end, the get_conversation api view will run to get their previous texts and then on the front-end the WebSocket will be used to dynamically update their screen with new texts they are currently sending using the send_message API view. Is my current logic/implementation the correct approach that is normally used or is there something that could be done differently? This is the API view I am using to send a message: @api_view(['POST']) @permission_classes([IsAuthenticated]) def send_message(request, receiver_id): sender = request.user content = request.data.get('content') # Ensures there is content within the message if not content: return Response({"error": "Message content is required"}, status=status.HTTP_400_BAD_REQUEST) # Ensures the receiving user exists try: receiver = User.objects.get(id=receiver_id) except User.DoesNotExist: return Response({"error": "Receiver not found"}, status=status.HTTP_404_NOT_FOUND) # Ensures the user is not sending … -
what am i doing wrong in Pagseguro API
I trying to use Pagseguro API sandbox on Django but it doesnt work I know that im passing the encryptedCard but the API cannot read it "charges": [ { "reference_id": "referencia da cobranca", "description": "descricao da cobranca", "amount": { "value": 500, "currency": "BRL" }, "payment_method": { "soft_descriptor": "WEBDESIGN", "type": "CREDIT_CARD", "installments": 1, "capture": True, "card": { "encrypted": request.POST['encriptedCard'], "security_code": "123", "holder": { "name": "Jose da Silva" }, "store": True } } } ] }) it returns {"error_messages":[{"code":"40002","description":"invalid_parameter","parameter_name":"charges[0].payment_method.card.encrypted"}]} Ive printed in terminal to see if it are be passing by post and it is but i cant figured out why the json dont reads -
Django: SUM of COUNT in annotations
I have the following simple models: class Member(models.Model): name = models.CharField(max_length=100) class Booking(models.Model): date = models.DateField(default=now) price = models.DecimalField(max_digits=7, decimal_places=2) organizer = models.ForeignKey(Member, on_delete=models.CASCADE) booked_for = models.ManyToManyField(Member, related_name="booking_claims") Now, in a view, I want to annotate my Members with infomation about the total spendings of a member (i.e. the sum of all prices of bookings where this member is the organizer) and the total claims from this member (i.e. the sum of all proportional costs of bookings where the member takes part in). Ideally, this would work as follows: members = Member.objects.annotate( total_spending=Sum("booking__price", default=0), total_claims=Sum(F("booking_claims__price") / Count("booking_claims")), ) However, I get an error that Count is an aggregate and I cannot use Sum on an aggregate. I know, there exist some related questions and I have already tried a lot of different things, including subqueries and custom Count functions but I can't get it to work. Is there someone that knows how to solve this? -
How to dumps Python object to JSON without "" using json.dumps()?
I need to request post a 36-digit id with other things to a url. This code should be sent as json. But when I try to json.dumps() it, the initial and final quotes are also counted and as you can see I reach 38 characters and get error. merchant_id='xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' merchand_id_json = json.dumps(merchant_id) #check len of merchat id and merchant id in json format print('len merchant_id is', len(merchant_id)) print('len merchand_id_json is', len(merchand_id_json)) # Set header request_header = { 'accept': 'application/json', 'content_type': 'application/json', } # Send request res = requests.post( url=request_url, data= { "merchant_id": merchand_id_json, }, headers=request_header) # Check res content in terminal print('res =', res) # Check res.text in terminal print('res.text =', res.text) in Terminal: len merchant_id befor json is 36 len merchand_id after json is 38 res = <Response [200]> res.text = {"data":[],"errors":{"code":-9,"message":"The input params invalid, validation error.","validations":[{"merchant_id":"The merchant id may not be greater than 36 characters."},{"merchant_id":"string is not a valid uuid."}]}} How can I convert this 36-digit id to json format without increasing the number of characters? -
Why am I getting MultiValueDictKeyError when using requst.files in Django?
I am trying to upload a file to my Django Server using HTML input type file. HTML Code <form action="csv/upload" enctype="multipart/form-data" method="POST"> {% csrf_token %} <input type="file" name="csvFile" accept=".csv"> <button type="submit">submit</button> </form> views.py def upstud(request): var = "0sdfs" my_uploaded_file = request.FILES["csvFile"] num = type(my_uploaded_file) return render(request, "signup.html", {"var": num}) On Submitting the file I get MultiValueDictKeyError at:- my_uploaded_file = request.FILES["csvFile"] I have tried using my_uploaded_file = request.FILES.get("csvFile"]) This simply returns none What is the issue? -
Staff user is getting by default all permission in Django Admin Site - Custom User Model (AbstractBaseUser)
I am using Django custom user model inheriting from AbstractBaseUser & PermissionsMixin. When I make a staff user, the user gets all the permission by default, means staff has superuser privileges of 'view', 'change', 'add', & 'delete' on all the apps and models in django admin site, But when I use Django's built-in User model it works perfectly fine, when a staff user login it says 'you don't have permission' and when I assign the permission I want to give the staff has the only permission in django admin site. my model has both methods with True has_perm() has_module_perms() Do I need to update something which is commonly made mistake? I tried changing has_perm and has_module_perms to return False but it restrict superuser also. -
How to locate django logs in nginx docker setup?
I have my website build using below technology stack, Django GraphQL Postgres Nginx Docker Below is how my docker-compose file looked like, version: "3.9" services: web: extra_hosts: - "host.docker.internal:host-gateway" build: context: . dockerfile: Dockerfile.prod command: gunicorn sports_league.wsgi:application --bind 0.0.0.0:8000 volumes: - .:/code - static_volume:/code/staticfiles - media_volume:/code/mediafiles environment: - PRODUCTION=true env_file: - ./config/.env.prod expose: - 8000 nginx: build: ./nginx ports: - "80:80" depends_on: - web volumes: - static_volume:/code/staticfiles - media_volume:/code/mediafiles volumes: pgdata: static_volume: media_volume: When I run the django app locally, I can see the logs (print statements) on terminal. However when I run it using Docker as a service, I don't see those in the container logs. It looks like nginx is causing this to happen. I check nginx container logs as well, but I cannot find the logs there as well. Below is how my nginx configuration file looks like, upstream sports_league { server web:8000; } server { listen 80; location / { proxy_pass http://sports_league; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; client_max_body_size 100M; } location /static/ { alias /code/staticfiles/; } location /media/ { alias /code/mediafiles/; } } Please help me to locate the logs or those print statements. -
TypeError at /cart/add_cart/7/ _cart_id() takes 0 positional arguments but 1 was given
from urllib import request from django.http import HttpResponse from django.shortcuts import render, redirect from .models import Cart, CartItem from store.models import Product Create your views here. def _cart_id(): cart = request.session.session_key if not cart: cart = request.session.create() return cart def add_cart(request, product_id): product = Product.objects.get(id=product_id) try: cart = Cart.objects.get(cart_id=_cart_id(request)) #get the cart using the cart_id present in the session except Cart.DoesNotExist: cart = Cart.objects.create( cart_id = _cart_id(request) ) cart.save() try: cart_item = CartItem.objects.get(product=product, cart=cart) cart_item.quantity += 1 #cart_item.quantity = cart_item.quantity + 1 cart_item.save() except CartItem.DoesNotExist: cart_item = CartItem.objects.create( product = product, quantity = 1, cart = cart, ) cart_item.save() return HttpResponse(cart_item.product) exit() return redirect('cart') def cart(request,): return render(request, 'store/cart.html') Hey, so basically when I'm running the server to test the "Add to cart" button I get this error. enter image description here -
Django missing underscore in models name from admin
I'm working on a project using Django cookie cutter I have an issue with adding a through model (EventCompetitor) to my app for additional info related to a many to many relationship (competitors). I can see in the db that the through table is called: "events_event_competitor" but Django throws an error in the admin because its trying to query: "events_eventcompetitor". django.db.utils.ProgrammingError: relation "events_eventcompetitor" does not exist what would cause this issue? models.py class EventCompetitor(models.Model): event = models.ForeignKey('Event', on_delete=models.CASCADE) competitor = models.ForeignKey(Competitor, on_delete=models.CASCADE) order = models.IntegerField(default=0) class Meta: unique_together = ('event', 'competitor') class Event(models.Model): """ Default custom evens model for oddsx. """ # Choices for the status field STATUS_CHOICES = [ ('CANCELLED', 'Cancelled'), ('LIVE', 'Live'), ('SCHEDULED', 'Scheduled'), ('POSTPONED', 'Postponed'), ('FINISHED', 'Finished'), ] name = models.CharField(verbose_name="Event name", max_length=30) slug = models.SlugField(verbose_name="Slug", max_length=30) sport = models.ForeignKey(Sport, on_delete=models.CASCADE) country = models.ForeignKey(Country, on_delete=models.CASCADE, related_name="events") competition = models.ForeignKey(Competition, on_delete=models.CASCADE, related_name="events", null=True) competitors = models.ManyToManyField(Competitor, through='EventCompetitor', through_fields=('event', 'competitor')) status = models.CharField(verbose_name="Status", max_length=10, choices=STATUS_CHOICES, default='SCHEDULED') start_date = models.DateTimeField(verbose_name="Start date", null=True, blank=True) venue = models.CharField(verbose_name="Venue", max_length=60, blank=True, null=True) city = models.CharField(verbose_name="City", max_length=80, blank=True, null=True) class Meta: verbose_name_plural = "Events" def __str__(self): return self.name admin.py @admin.register(Event) class EventAdmin(admin.ModelAdmin): prepopulated_fields = {"slug": ("name",)} list_display = ("name", "slug", "country", "sport") list_filter = … -
Optimizing Django Social Media App: Efficient Handling of Profile Privacy and Pagination Logic for Post Retrieval
I am new to Djnago and I am designing my first Social Media App, so I am a bit new to this. I have an API view to get a users profile and their posts. I have implemented logic to check if the requesting user is able to view another users posts based on their profile_privacy and if the requesting user follows them or not. If the requesting user is able to view the users posts, then and only then we query for their posts. My question is: Since the posts are paginated, when the user requests for the profile, it will perform the logic and then get the appropriate posts, however, when we query for the second page of Post data, it will perform the same logic and checks again (check the follow instance to see if the requesting user follows them). Instead of performing this logic for every page query, is there a way to check it only once since for all other page requests we know the user already follows them? One approach was checking if the page being requested is the first page and only perform the checks for that, but that introduces security issues since … -
Getting Origin is not allowed by Access-Control-Allow-Origin when using Django authentication on one url but all origins are allowed
I am running into issues with CORS on Django and React (fetch). Django is set up like this: INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "rest_framework", "corsheaders", "users", ] 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", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] CORS_ORIGIN_ALLOW_ALL = True ALLOWED_HOSTS = ['*'] CORS_ORIGIN_WHITELIST = ( "http://localhost:3000", "http://127.0.0.1:3000", ) The urls in users: urlpatterns = [ path('login/<str:username>/<str:password>/', login), path('logout/', logout), path('info/', info), ] and views from rest_framework.decorators import api_view from rest_framework.response import Response from django.contrib import auth from django.http.response import HttpResponse # Create your views here. @api_view(['GET']) def login(request, username, password): user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) return Response('yes') else: return Response('no') @api_view(['POST']) def logout(request): auth.logout(request) return Response('hmmmmmmm') @api_view(['GET']) def info(request): if request.user.is_authenticated: return HttpResponse('wow, this is really critical information: 5!') else: return HttpResponse('nothing here...') When I do a request from react let [message, setMessage] = useState('waiting...') fetch('http://localhost:8000/users/login/Timoty/foo') .then(res => res.text()) .then(text => setMessage(text)) I get the typical error... What puzzles me the most is the fact that this is a cors issue, I am thinking that maybe I need to do some cookie magic from my react code, but why am I getting cross origin errors then? It … -
Change django.forms.models.ModelChoiceIterator
The choices variable of one of my fields (django.forms.models.ModelChoiceIterator) in ModelForm contains 3 items. In some cases, I want to use only one of them (the first one in the "list") for the actual HTML. Here's a part of the Django Python code: class MyForm(ModelForm): def __init__(self, *args, user=None, **kwargs): choices = self.fields['xxx'].choices qs = choices.queryset qs = qs[:1] ... ... self.fields['xxx'] = forms.ChoiceField( label="xxx", widget=forms.Select( attrs={ 'class': 'form-select' } ), self.fields['xxx'].choices = choices self.fields['xxx'].choices.queryset = qs class Meta: ... model = MyModel fields = ('xxx') ... This throws an error : 'list' object has no attribute 'queryset'" and, obviously, the size and content of choices do not change. choices is an instance of django.forms.models.ModelChoiceIterator How can I reduce the number of items in the choices which will be displayed in the HTML ? -
OSError: /home/ahmad/miniconda3/envs/python3.6/bin/../lib/libstdc++.so.6: version `GLIBCXX_3.4.30' not found (required by /lib/libgdal.so.30)
Title: Error in Miniconda Virtual Environment on Ubuntu 22.04 Description: I recently upgraded my Ubuntu system from 20.04 to 22.04 and encountered an issue my project was running smoothly on Ubuntu 20.04, but after the upgrade, I'm facing the following error: ruby Copy code OSError: /home/ahmad/miniconda3/envs/python3.6/bin/../lib/libstdc++.so.6: version `GLIBCXX_3.4.30' not found (required by /lib/libgdal.so.30) I have tried several solutions I found online, including installing build essentials, Python development headers, and even creating a new virtual environment, but the issue persists. Here are some key details: I'm using Miniconda to manage my Python environment. I have created a virtual environment with Python 3.6 for my Django project. I would greatly appreciate any guidance or solutions to resolve this issue and successfully install GDAL in my virtual environment on Ubuntu 22.04. Thank you for your help! -
Getting Error cors "Request header field responsetype is not allowed by Access-Control-Allow-Headers in preflight response" in django
Error in the browser console Access to XMLHttpRequest at 'https:///some_site/resource1/downloadCSV' from origin 'https://some_site' has been blocked by CORS policy: Request header field responsetype is not allowed by Access-Control-Allow-Headers in preflight response. check the API Method @api_view(["POST"]) def downloadCSV(request): request_body = request.data response = HttpResponse( some_service.call_some_other_service(), content_type="application/octet-streamf", ) today = datetime.today().strftime("%Y-%m-%d") filename = f"{today}_Data.csv" response["Content-Disposition"] = f'attachment; filename="{filename}.csv"' return response main/settings.py INSTALLED_APPS = [ ............. "corsheaders", ........ ] MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware", ] CORS_ORIGIN_ALLOW_ALL = True I can't do it because the other response type header is failing, Please suggest how to allow the responseType =bob so that I will able to download API. CORS_ALLOW_HEADERS = [ # ... 'responsetype', # ... ] -
winerror 5 access denied
i am setting up a virtual environment for django and when i use python -m venv djangoenv a winerror 5 pops up to tell me acess denied please i need help with this. i have been trying the whole day with different versions of vscode and i get the same message. i dont know if it has something to do with the path or i am not just during it right.i am a beginner and i can't seem to spot what exactly the problem is -
Creating and saving a model object with a calculated m2m field Django
New to Django, I don't know if it's still worth it. I'm currently trying to save a model form with a many-to-many field that should be set randomly according to other fields(category, subcategory, number) in the same form. how do I get it to work? class Exam(models.Model): categ=models.ManyToManyField(Category,blank=False) sscateg = models.ManyToManyField(SubCategory,blank = True,null= True) question = models.ManyToManyField (Question,related_name='questionsEx',blank=False) nbquestion = models.IntegerField() def save(self, *args, **Kwargs): super(Exam, self).save(*args,**Kwargs,commit=False) if self.pk: qs=Question.objects.filter(category=self.categ).filter(sscateg=self.sscateg).values_list('id',flat =True) questions = random.sample(qs,self.nbquestion) for quest in questions: self.question.add(quest) super(Exam, self).save(*args,**Kwargs) forms.py class ExamForm(forms.ModelForm): nbquestion = forms.IntegerField(required = False) categ=forms.ModelChoiceField(Category.objects.all(), widget=forms.CheckboxSelectMultiple,required = False) sscateg=forms.ModelChoiceField(SsCategory.objects.all(), widget=forms.CheckboxSelectMultiple,required=False) def save(self, commit=True): instance = forms.ModelForm.save(self, False) self.save_m2m() instance.save() return instance views.py class ExCreateView(LoginRequiredMixin, CreateView): login_url = 'login' template_name = 'MakeEx.html' model = Exam form_class = ExamForm success_url = reverse_lazy('Exams') def form_valid(self, form): instance=form.save(commit=False) instance.save() form.save_m2m() return super(ExCreateView,self).form_valid(form) -
image path is incomplete django
in my-projet (django) The image path is incomplete in some api How can i fix it like when i use this api (categories) i got this Response Note that the image path is complete [ { "id": 1, "name_ar": "تطبيقات توصيل", "name_en": "weew", "icons": "http://127.0.0.1:8000/media/catecgorys/cloud123333_ZCE0xex.svg" }, { "id": 2, "name_ar": "متاجر", "name_en": "stores", "icons": "http://127.0.0.1:8000/media/catecgorys/cloud123333_BSbQU6b.svg" }, ] but when i use some api the entire image path is not displayed like how i can fix it ? { "status": "True", "data": [ { "id": 1, "code": "444", "percentage": "10%", "store": { "id": 1, "name_ar": "", "name_en": "noon", "description": "sdsdsdsdsdsdsd", "url": "noon.com", "logo": "/media/logo/Noon_log.jpeg", "categories": [ { "id": 1, "name_ar": "category 1", "name_en": "category 1", "icons": "/media/Categories/cloud123333.svg" } ] }, "description": "", "type": "", "ratings": { "id": 2, "likes": 1, "dislikes": 1 } } ] } my code : class GetCouponsByCategoryAPIView(viewsets.ModelViewSet): permission_classes = [permissions.AllowAny] queryset = Coupons.objects.all() serializer_class = CouponsSerializer def post(self, request, *args, **kwargs): categorys_id = request.data.get("Categories_id") if not categorys_id: return Response({"error": "Categories_id parameter is required."}, status=status.HTTP_400_BAD_REQUEST) try: category = Categories.objects.get(id=categorys_id) stores = Stores.objects.filter(catecgorys=category) except Categories.DoesNotExist: return Response({"status": "False", "error": "Category not found."}, status=status.HTTP_404_NOT_FOUND) except Stores.DoesNotExist: return Response({"status": "False", "error": "Store not found."}, status=status.HTTP_404_NOT_FOUND) coupons = Coupons.objects.filter(store__in=stores) serializer = CouponsSerializer(coupons, …