Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
When I run python manage.py test... only some of my tables / fields are created in the test db
In django, I am trying to run tests on a test db, but I can't seem to get the test db stood up properly... I have 226 models on my real db, but when I run python manage.py test (test location) it breaks pretty quickly referencing that a field is not present in the test db. psycopg2.errors.UndefinedColumn: column core_division.display_name does not exist A quick look at the test db (since it crashes, it doesn't teardown the db, so I can view it) shows only 47 tables created, and sure enough that particular field is not there. Below is my database settings in my config.settings.test file: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'myscore', 'USER': env('DEFAULT_DATABASE_USER'), 'PASSWORD': env('DEFAULT_DATABASE_PASSWORD'), 'HOST': 'localhost', 'PORT': '', 'TEST': { # 'MIRROR': 'default', 'SERIALIZE': False, # 'MIGRATE': False, } }, } What I tried to do as a workaround was apply the 'MIGRATE': False option. When I do this (with --keepdb applied), I see that the test db has 195 tables (and does have the field that wasn't created before). So this is better. No failures / crashes. However...I can't seem to write / read anything from the db and I'm not sure why... So...what I've … -
How to serialize request.user for ModelSerializer to auto fill the user field in Model?
This question is not good question but, I spent 6 hours to solve this problem, searching in stackoverflow and still problem is bother me. I have a model as below : class Product(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=144, primary_key=True, unique=True) description = models.CharField(max_length=144) def __str__(self) -> str: return self.title and its serializer : class ProductSerailizer(serializers.ModelSerializer): class Meta: model = Product fields = "__all__" exclude = ["user"] and my view is like below : class CreateProduct(generics.GenericAPIView): """""" serializer_class = [ProductSerailizer] permission_classes = [permissions.IsAuthenticated] def perform_create(self, serializer): return self.serializer(user=self.request.user) def post(self, request, *args, **kwargs): user_serializer = UserSerializer(data=request.data) if user_serializer.is_valid(): user_serializer.save() return response.Response(user_serializer.errors, status=status.HTTP_400_BAD_REQUEST) I wanna auto fill the user by the request, but when I send the request with postman it says : "username": [ "A user with that username already exists." ] and it doesn't save my instance. I don't know how to handle this. I wanna type this with generics. Can anyone help me out ? -
How do I display non field errors and field errors after I hit the submit form button for user sign up?
I would like to display Form.non_field_errors() and Form.errors upon submitting my form. It has email, password and confirm password fields. The thing is, I want all errors to show up if the inputs for these fields are wrong. (e.g. invalid email, passwords don't match). However, I am facing the issue that upon submission of my form when all fields are wrong, only the non_field_errors() show up first. Once that has been resolved and I clicked enter again, the field errors then show up. I don't want them to show up 1 by 1 and prefer that they show up altogether. Issue on my form (Only Enter a valid email address is showing up, no password errors when there should be upon submitting) Here's my code. forms.py class UserRegistrationForm(forms.ModelForm): password2 = forms.CharField( label="New password confirmation", widget=forms.PasswordInput(attrs={"autocomplete": "new-password"}), ) class Meta: model = User fields = [ "email", "password", ] def _validate_passwords(self, password1, password2): password_errors = [] try: validate_password(password1, self.instance) except ValidationError as e: password_errors.append( ValidationError(_("Weak password provided"), code="weak-password"), ) if password1 and password2 and password1 != password2: password_errors.append( ValidationError(_("Passwords mismatch"), code="password-mismatch"), ) if len(password_errors) > 0: raise ValidationError(password_errors) def clean(self): cleaned_data = super().clean() email = cleaned_data.get("email") password1 = cleaned_data.get("password") password2 = … -
My Python Django button is not appearing when someone logs in(it should be)
I am working on a Python Django project. I'm currently working on a way for myself to log in and create a product card for this project store. The create button should only appear when I am logged in. It's just not appearing. I go to Inspect the web page and I don't even see the code for my button. I have no idea what is happening and some help would be awesome! This is the block of code that should be producing said button. If the user is authenticated, it'll create this create button under each one of my categories. I originally had the for statement over the if statement and I switched it to see if that would change anything and nothing happened. HTML {% if user.is_authenticated %} {% for category in categories %} <p>User is authenticated: {{ user.username }}</p> <!--LINE FOR DEBUGGING--> <p>Category: {{ category.name }}</p> <!--LINE FOR DEBUGGING--> <a class="create_button" href="{% url 'create_product' category.id %}">Create {{ category.name }}</a> {% endfor %} {% endif %} One of the first things I did I was add some debugging lines to see if it actually understood I was logged in. HTML <div> {% if user.is_authenticated %} <p>User is authenticated: … -
Why does my django-project work when I change my secret_key?
I change my SECRET_KEY in django project, and i start it again using manage.py runserver, but project is still working. How is it possible,? I think the project should not work. I try replace SECRET_KEY from .env back to settings.py. But it doesn`t help. -
I need to run migrations as a part of an MS Azure app service release pipeline for a Django web app
I need to execute the migration command on the container hosted on azure webapp python3 manage.py migrate I have tried using POST_BUILD_SCRIPT_PATH which points to the shell script file which has the command I tried passing the command using startup command from both cd pipeline as well as configuration but both of the approaches didn't help Did anyone succeeded with this? As I'm stuck from a day on the same.. I'm expecting a working solution for this issue who has done recently or who is familiar with this stuff -
Cookie on the same domain is set, but not being sent to another subdomain
I have a django server running on api.domain.lt and sveltekit server running on dev.domain.lt. Due to the separate servers I have a endpoint /csrf that forces to set a cookie if there's none for the frontend, so I could perform any kind of POST requests later. As I can see in the response headers the cookie is being set: Set-Cookie csrftoken=d8nimJM2fXtyPdhra2h8oF36o7juCJKz; Domain=.domain.lt; expires=Tue, 28 Jan 2025 17:35:19 GMT; Max-Age=31449600; Path=/; SameSite=Lax; Secure But when I perform another request to the server the cookie is not being added to the request,for god damn sakes, whyyyyyy? Even if I open the django server in another tab and view the Cookies in the dev tools, there's nothing. CORS_ALLOWED_ORIGINS = [ "https://domain.lt", "https://dev.domain.lt", "https://api.domain.lt", ] CSRF_TRUSTED_ORIGINS = [ "https://domain.lt", "https://dev.domain.lt", "https://api.domain.lt", ] # This allows us to send requests from dev.domain -> api.domain CORS_ALLOW_CREDENTIALS = True CSRF_COOKIE_SECURE = True # The cookie will be marked as “secure”, which means browsers may ensure that the cookie is only sent under an HTTPS SESSION_COOKIE_SECURE = True # Is this actually doing anything? CSRF_COOKIE_DOMAIN = ".domain.lt" SESSION_COOKIE_DOMAIN = ".domain.lt" This is how I perform a request to the django server: const res = await fetch( "https://api.domain.lt/........", {credentials: … -
Python Django(?) ORM race conditions
The answer to my question may probably be obvious, but I'd like to find out for myself. I love Django ORM and use it in almost all my projects. I'm currently developing a telegram bot using Pyrogram (available in asynchronous mode with async await + asyncio.run), and I want to use Django ORM in it. Let me give a simplified example of my task. There is a button that is bound to an object in the database, each click of which should decrease a field in one object and increase another field in another, conditionally: obj1 = Object1.objects.get(id=X) if obj1.filed1 > 0: obj2 = Object2.objects.get(id=X2) obj1.field1 += N obj2.field2 += N obj1.save() obj2.save() However, I am worried that this may cause a race condition and the result of executing this code with several simultaneous button clicks may differ from what is expected (both in the if condition and when further saving objects). Please tell me what are the best practices for handling such tasks. Is select_for_update method would cover me needs? If Django ORM is not a good solution for this, what ORMs or database libraries should I look at? If Django ORM is suitable, what exactly is the best … -
appication.view is not getting import in django urls using python community edition please help out
i have been making a django project using pycharm community edition i did install application in settings.py it is not getting import in django urls.py from productapp.Views import Home productapp is my app name and this is query ive writen in django.urls file expecting it to get import in my urls file -
Why is my get_token() not the same as my request.META.get("CSRF_COOKIE")?
Does anyone know why I am encountering this issue? I'm starting to test Angular 17 as a FrontEnd with Django as a Backend, and when validating a form, I encounter the issue that when obtaining my token from Django and sending it in the HTTP header, it doesn't match the token expected by Django. I'm not sure if the problem is that the expected token is not updating with get_token() or if get_token() is returning the incorrect token. settings.py: CSRF_TRUSTED_ORIGINS = [ "http://localhost:4200", ] CSRF_COOKIE_NAME = 'XSRF-TOKEN' CSRF_USE_SESSIONS = True CSRF_COOKIE_SECURE = True CSRF_COOKIE_HTTPONLY = True CSRF_COOKIE_DOMAIN = 'localhost' CSRF_COOKIE_PATH = '/' #En esta sección configuro el CORS CORS_ORIGIN_WHITELIST = [ "http://localhost:4200", ] CORS_ALLOWED_ORIGINS = [ "http://localhost:4200", # Angular ] CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_METHODS = [ 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ] CORS_ALLOW_HEADERS = [ 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'X-XSRF-TOKEN', 'x-requested-with', 'Content-Type', '_HttpHeaders', ] csrf-service.service.ts export class CsrfService { private csrfToken: string | null = null; constructor(private http: HttpClient) {} //Obtener el token CSRF getCsrfToken(): string | null { return this.csrfToken; } //Cargar el token CSRF desde el servidor loadCsrfToken(): Observable<any> { const csrfUrl = 'http://localhost:8000/obt_csrf_token/'; return this.http.get<any>(csrfUrl); } //Actualizar el token CSRF en el … -
Django - Cannot Display Elements Based On Field Value
I’m currently building a gaming app where a currently logged in user has access to play different games based on their rank in our application. So if a currently logged in user has a rank of let’s say 100 than all the games with a game rank of 100 and below will be displayed. The rest of the games will be locked. I can’t get this currently fully to work with my code. What do I need to change with my code? If I test using When(game_rank__lte=25, then=Value(True)), that seems to work, I can see both locked and unlocked games based on the value of 25 and less. But when I do When(game_rank__lte=user_profile_rank, then=Value(True)), that doesn’t seem to work. All the games are unlocked and none are locked. The rank of each game is the game_rank field in the Game_Info model. The rank of the currently logged in user is the rank field in the User_Info model. Any help is gladly appreciated. Thanks! models.py class Game_Info(models.Model): id = models.IntegerField(primary_key=True, unique=True, blank=True, editable=False) game_title = models.CharField(max_length=100, null=True) game_rank = models.CharField(max_length=1000, null=True, blank=True) game_image = models.ImageField(default='default.png', upload_to='game_covers', null=True, blank=True) locked_game = models.BooleanField(default=0) unlocked_game = models.BooleanField(default=0) class User_Info(models.Model): id = models.IntegerField(primary_key=True, blank=True) image … -
ImportError: attempted relative import beyond top-level package in Django while importing from different django apps
I am trying to import SignUp model from authentication app into views file of another app named core. Why i am getting this error and how can i solve this? core/views.py from django.http import HttpResponse from django.shortcuts import render from mongoengine import DoesNotExist from ..authentication.models import SignUp def home(request): default_content = { 'title': 'Welcome to College Management System', } # Retrieve the user_id and username from cookies user_id = request.COOKIES.get('user_id') username = request.COOKIES.get('username') if user_id: try: user = SignUp.objects.get(username=username) # Your existing code that uses user_id goes here # For example, you can fetch additional user data using user_id # Update default_content or perform other actions based on user information except DoesNotExist: # Handle the case where the user does not exist return HttpResponse("User does not exist") return render(request, 'core/base.html', {'content': default_content, 'username': username}) authentication/models.py import mongoengine from django.contrib.auth.hashers import check_password class SignUp(mongoengine.Document): email = mongoengine.EmailField() username = mongoengine.StringField(max_length=15) password = mongoengine.StringField() first_name = mongoengine.StringField(max_length=20) last_name = mongoengine.StringField(max_length=20) role = mongoengine.StringField(choices=('admin', 'faculty', 'student')) meta = { 'collection': 'Signup', } def check_password(self, raw_password): return check_password(raw_password, self.password) -
An error occurred (403) when calling the HeadObject operation: Forbidden - Why I'm receiving this error when I try to post an item at AWS S3?
I'm working in an e-commerce Django project and I've made the deployment of the project in an EC2 instance, but now that I'm trying to work again at my Django project I'm receiving this error when I try to create a new item ClientError at /items/new/ An error occurred (403) when calling the HeadObject operation: Forbidden Note that I've tried several different types of bucket policies and no one have work Bucket Policy -> { "Version": "2008-10-17", "Statement": [ { "Sid": "AllowPublicRead", "Effect": "Allow", "Principal": "*", "Action": "s3:*", "Resource": [ "arn:aws:s3:::ecommercesimple", "arn:aws:s3:::ecommercesimple/*" ] } ] } settings.py -> # Amazon S3 settings AWS_ACCESS_KEY_ID = 'xxxxx' AWS_SECRET_ACCESS_KEY = 'xxxx' AWS_STORAGE_BUCKET_NAME = 'ecommercesimple' AWS_S3_SIGNATURE_NAME = 's3v4', AWS_S3_REGION_NAME = 'us-east-2' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None AWS_S3_VERITY = True DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' I appreciate any help! -
Can't solve problem "Page not found (404)" in Django
I have this problem and can not fix it. project = test_dummy app = database This is the error message that I get: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/templates/htmlcode/homeAntragsteller.html Using the URLconf defined in test_dummy.urls, Django tried these URL patterns, in this order: admin/ [name='login'] [name='index_antragsteller'] The current path, templates/htmlcode/homeAntragsteller.html, didn’t match any of these. database/urls.py urlpatterns = [ path('', views.user_login, name='login'), path('', views.index_antragsteller, name='index_antragsteller'), ] test_dummy/urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include("database.urls")), ] my views.py for user_data in example_users: User.objects.get_or_create(email=user_data['email'], password=user_data['password'], telefonnummer=user_data['telefonummer'], vorname=user_data['vorname'], ist_bearbeiter=user_data['ist_bearbeiter'], name=user_data['name'], abteilung=user_data['abteilung']) def user_login(request): create_example_users() if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data['email'] password = form.cleaned_data['passwort'] if User.objects.filter(email=username).exists(): user_eintrag = User.objects.get(email=username) if user_eintrag.password == password: print("Passwort correct") if user_eintrag.ist_bearbeiter: return redirect('../templates/htmlcode/homeBearbeiter.html') else: return redirect('templates/htmlcode/homeAntragsteller.html') else: if user_eintrag.password != password: return redirect('../templates/htmlcode/login.html') else: return redirect('../templates/htmlcode/error.html') else: return render(request, '../templates/htmlcode/login.html') @login_required def index_antragsteller(request): return render(request, '../templates/htmlcode/homeAntragsteller.html') in the view, I also tried to remove ../ from ../templates/htmlcode/homeAntragsteller.html but it doesn't look like it's having any effect. my folder structure . ├───database │ ├───migrations │ ├───views.py │ └───urls.py ├───test_dummy │ ├───static │ │ └───filesCSS │ ├───templates │ │ ├───bilder │ │ ├───htmlcode │ | | └───homeAntragsteller.html │ │ └───scripts … -
How to set next_url in Middleware?
I'm writing a custom piece of Middleware for my Django project that will redirect every page request to an age gate if the user has not yet confirmed they are old enough to enter the page. I want the age gate page to redirect to their originally requested page when they have confirmed the age gate. My middleware right now looks as follows: from django.shortcuts import redirect class AgeGateMiddleware: EXCLUDED_URLS = ['/preview/agegate'] def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if not request.session.get('agegate') and request.path not in self.EXCLUDED_URLS: request.session['next_url'] = request.path return redirect('/preview/agegate') response = self.get_response(request) return response And my age gate view looks like this: def age_gate_view(request): #Load the original page after checking age gate. next_url = request.session['next_url'] #Register users IP for age gate. x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') try: ip =ip except: ip = 'none' form = AgeGateForm({'ip':ip}) #Store age gate response if request.method == 'POST': form = AgeGateForm(request.POST or None, {'ip':ip}) if form.is_valid(): form.save() request.session['agegate'] = 'welcome' return redirect(next_url) context = { 'form':form, } return render(request,'Academy/agegate.html', context) Right now the Middleware works as intended: It redirects to the age gate if this has not yet been confirmed. However: The … -
Django User Is Logged Out outside the home page
I have a django website. Now the problem is, after I sign in as a User or an Agent, the correct links only show up on my home page. Whenever I visit another page, the correct links are gone and are replaced with 'Sign In' and 'Agent Sign In'. Somehow the user is logged out outside of the home page. How can I solve this? Thanks in advance! My models.py: class CustomUser(AbstractUser): email = models.EmailField(unique=True) groups = models.ManyToManyField(Group, related_name='CustomUser_set', blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.') user_permissions = models.ManyToManyField(Permission, related_name='customuser_set', blank=True, help_text='Specific permissions for this user.') is_user = True class Profile(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) phonenumber = models.IntegerField() def __str__(self): return f'{self.user.username} Profile' class Agent(AbstractUser): username = models.CharField(max_length=100, unique=True) name = models.CharField(max_length=100) agent_email = models.CharField(max_length=100, unique=True) password = models.CharField(max_length=200) image = models.ImageField(upload_to = 'Images/') bio = models.TextField() instagram = models.URLField(max_length=100) twitter = models.URLField(max_length=100) facebook = models.URLField(max_length=100) linkedin = models.URLField(max_length=100) is_featured = models.BooleanField(default = False) last_login = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) slug = AutoSlugField(populate_from='name') is_staff = models.BooleanField(default=False) groups = models.ManyToManyField(Group, related_name='agent_set', blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their … -
nginx proxy_pass not passing request to docker app on port 8000
Here is my nginx.conf file: server { listen 80; server_name example.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/../staticfiles; } location /api/ { include proxy_params; proxy_pass http://127.0.0.1:8000; } } I checked whether my app is running on port 8000 through docker ps command. Here is the log: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES f86d5f013c90 lead-hr-api-backend "bash -c ./run.sh" 18 hours ago Up 18 hours 0.0.0.0:8000->8000/tcp, :::8000->8000/tcp lbhr-backend Nginx error logs: sudo tail -F /var/log/nginx/error.log 2024/01/30 11:51:53 [error] 59675#59675: *283 recv() failed (104: Unknown error) while reading response header from upstream, client: 172.69.165.44, server: leadhr.alexpy.com, request: "GET /api/admin/ HTTP/1.1", upstream: "http://127.0.0.1:8000/api/admin/", host: "example.com", referrer: "https://example.com/api/admin/login/?next=/api/admin/" 2024/01/30 11:52:16 [error] 59675#59675: *283 recv() failed (104: Unknown error) while reading response header from upstream, client: 172.69.165.44, server: leadhr.alexpy.com, request: "GET /api/admin/ HTTP/1.1", upstream: "http://127.0.0.1:8000/api/admin/", host: "leadhr.alexpy.com" Later I dug a bit deeper and found the Unknown error was connection reset by peer. I don't remember how I found the error, but it was that. Interestingly, when I run my api server using gunicorn, it works perfectly. -
Adding new data in the database
Validation error for trade - Sheet None: [{'identifier': [ErrorDetail(string='trade with this identifier already exists.', code='unique')]}, I'm trying to save a list of dictionaries in the database, which I will get from a file. The idea is that if a user upload the same file with just some new data, only the new data needs to be saved. from rest_framework import serializers from apps.trades.models import Trade from rest_framework import serializers class TradeSerializer(serializers.ModelSerializer): class Meta: model = Trade fields = ['identifier', 'issue_date', 'maturity_date', 'invested_amount', 'interest_rate'] -
How can i make ManyToMany admin pannel on django?
I made a ManyToManyField in Django, but it dosen't seem like i can edit it in django admin. After reading some documents, I found out that I needed to add some kind of widget, so I added filter_horizontal=('collections',) (which was shown in Django Admin ManyToManyField) but this seems to cause an error. Here are some codes I used. # models.py class Product(models.Model): date_added = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=200) price = models.DecimalField(max_digits=7, decimal_places=2) digital = models.BooleanField(default=False,null=True, blank=True) image = models.ImageField(null=True, blank=True) description = models.CharField(max_length=1000, null=True, blank=True) description_image = models.ImageField(null=True, blank=True) def __str__(self): return self.name @property def imageURL(self): try: url = self.image.url except: url = '' return url @property def descriptionImageURL(self): try: url = self.description_image.url except: url = '' return url ... class Collection(models.Model): title = models.CharField(max_length=200, null=False) product = models.ManyToManyField(Product, related_name='collections', blank=True) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title # admin.py from django.contrib import admin from .models import * admin.site.register(Customer) admin.site.register(Product) admin.site.register(Order) admin.site.register(OrderItem) admin.site.register(ShippingAddress) admin.site.register(TextBanner) admin.site.register(FocusSection) class CollectionAdmin(admin.ModelAdmin): filter_horizontal = ('collections',) admin.site.register(Collection, CollectionAdmin) which casues error : <class 'store.admin.CollectionAdmin'>: (admin.E019) The value of 'filter_horizontal[0]' refers to 'collections', which is not a field of 'store.Collection'. I would really appreciate your help. -
Dockerizing Django and Nginx - How can I Retrieve the Client IP Instead of the Bridge Network Gateway IP in Django with Docker?
I'm currently facing an issue with my Django application where, despite including the X-Real-IP and X-Forwarded-For headers in the request, I am still retrieving the gateway IP instead of the actual client IP. I have implemented a middleware to print the headers, and the logs consistently show the gateway IP. Here's a snippet of the relevant headers from the middleware logs: DebugHeadersMiddleware ================================== django_app | HTTP_X_REAL_IP : 172.30.0.1 django_app | HTTP_X_FORWARDED_FOR : 172.30.0.1 django_app | HTTP_HOST : localhost django_app | REMOTE_ADDR : 172.30.0.4 =========================================================== expected HTTP_X_REAL_IP or HTTP_X_FORWARDED_FOR to contain the client's IP, but it seems that the gateway IP is being retained. Current Nginx Configuration: upstream app { server web:8000; #container:port or host:port } server { listen 80; location / { proxy_pass http://app; # pass the request to django # allow django to know the client address proxy_set_header X-Real-IP $remote_addr; #* proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; # pass the host name } location /static/ { alias /app/static/; } location /media/ { alias /app/media/; } error_log /var/log/nginx/error.log; access_log /var/log/nginx/access.log; } my docker-compose : version: '3.9' services: db: # database config ... web: build: ./src volumes: - ./volumes/data/static:/app/static - ./volumes/data/media:/app/media - ./volumes/log/gunicorn/:/log/gunicorn/ env_file: - .env expose: - "8000" depends_on: - … -
Find graphene mutation/query from WSGIRequest it self
I have a middleware class that's before the request reaches the code itself, I want to figure out what mutation/query is begin called here class CustomMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): <--- how to figure it out using the WSGI request data = self.doTheMagic(request) if data: request.data = data response = self.get_response(request) return response -
How to reuse method for different classes?
I have a django app and I have two classes in models.py with an image attribute. And I have some functionality for cropping images in the save method. But the functionality is in both save methods almost identical. models.py: This is class: Animal: class Animal(models.Model): images = models.ImageField( upload_to="media/photos/animals", blank=False, null=False, verbose_name="Foto") def save(self, *args, **kwargs): # Opening the uploaded image if not self.images: return im = Image.open(self.images) if im.mode == "JPEG": pass elif im.mode in ["RGBA", "P"]: im = im.convert("RGB") output = BytesIO() original_width, original_height = im.size elif original_height == original_width: desired_width = 200 desired_height = 200 im = im.resize((desired_width, desired_height), Image.LANCZOS) im.save(output, format='JPEG', subsampling=0, quality=95) output.seek(0) self.images = InMemoryUploadedFile(output, 'ImageField', "%s.jpg" % self.images.name.split('.')[ 0], 'image/jpeg', sys.getsizeof(output), None) super(Animal, self).save() And I have a class Category: class Category(models.Model): images = models.ImageField( upload_to="media/photos/categories", blank=True, null=True, verbose_name="Foto") def save( self, force_insert=False, force_update=False, using=None, update_fields=None ): self.slug = slugify(self.name) if not self.images: return im = Image.open(self.images) if im.mode == "JPEG": pass elif im.mode in ["RGBA", "P"]: im = im.convert("RGB") output = BytesIO() original_width, original_height = im.size elif original_height == original_width: desired_width = 200 desired_height = 200 im = im.resize((desired_width, desired_height), Image.LANCZOS) im.save(output, format='JPEG', subsampling=0, quality=95) output.seek(0) self.images = InMemoryUploadedFile(output, 'ImageField', "%s.jpg" % … -
Django Allauth Facebook login send me to "login cancelled" page
I am making an app in Django and using the allauth library to enable Facebook login. I set up everything accordingly in my Django project and the FB Developer console (I am pretty sure of this because my Google login works), but when I click on the "Login with Facebook button", a popup window appears with a Facebook page asking me to login, but my app is already in the login cancelled page in the following URL: "https://www.xxxxxxxxxxxxxx.com/accounts/social/login/cancelled/". If I login in the popup window nothing changes in my app and the popup just closes. The weirdest thing is that I am not getting any error or warning logs. This happens both in development and production mode. I read in other posts that adding "ACCOUNT_DEFAULT_HTTP_PROTOCOL = 'https'" in settings.py can solve the issue, but it did not work for me. Has anyone had a similar problem and know the solution to this? -
Django Rest Framework - Vue js - axios , i cant send session Cookie at DRF api
i try to do a simple session authentication with "django.contrib.auth.urls". While i can login and i recieve a session id and csrf, the first time i login sends at request the cookie when i perform an axios get request, but when i try to login from another account does not send the cookie and i receive error code 401 when i perform a get requst with axios.(I work at development server). I mention also that every time i can do login succesfully and i receive session id and csrftoken but not include them at get request. Here is the settings.py: """ Django settings for inventoryapi project. Generated by 'django-admin startproject' using Django 5.0. For more information on this file, see https://docs.djangoproject.com/en/5.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/5.0/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/5.0/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 # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', … -
How to re-implement Django Authentication middleware
Current 'django.contrib.auth.middleware.AuthenticationMiddleware', Is logging in the user and such but using different JWT token from different generated sources (ex apple google github) will not work with this one because it's accepting only and only the one from GRAPHQL_JWT = { "JWT_ALLOW_ANY_CLASSES": [ "graphql_auth.mutations.Register", "graphql_auth.mutations.ObtainJSONWebToken", ], "JWT_VERIFY_EXPIRATION": True, "JWT_LONG_RUNNING_REFRESH_TOKEN": True, "JWT_EXPIRATION_DELTA": timedelta(days=365), "JWT_REFRESH_EXPIRATION_DELTA": timedelta(days=365), } I've already implemented a custom middleware "CustomAuthenticationMiddleware" and It works fine but I need to remove the already existing auth middleware and I get this error django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: ?: (admin.E408) 'django.contrib.auth.middleware.AuthenticationMiddleware' must be in MIDDLEWARE in order to use the admin application.