Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I host a Django application for free?
I have made APIs for my project Now I want to host it, but I am using MySQL workbench for the database. Is it possible to host it from render? or any better option to do so please give me the solution. So can I host from Render? or any other easy method? -
How to get value of variable from one funtion to another in python?
This is first Funtion: def signup(request): if request.method == "POST": username = request.POST['uname'] first_name = request.POST['fname'] last_name = request.POST['lname'] email = request.POST['email'] pass1 = request.POST['pass1'] pass2 = request.POST['pass2'] This is second function: def createPost(request): if request.method == "POST": form = PostForm(request.POST) print(form.is_valid()) if form.is_valid(): # To extarct data from web page title = form.cleaned_data['title_name'] description = form.cleaned_data['description'] print(title) # To store Data PostData.objects.create(title_name=title, description=description) How to get value of 'username' from first function to second function? -
Django app log messages not appearing in ECS/CloudWatch
Issue: I have a Django project deployed on ECS, and I am experiencing issues with my logging configuration. I am unable to see my custom logging messages in AWS CloudWatch Logs. The only log messages I can see are from botocore, urllib3, and root loggers. My custom log messages are not appearing at all. Current Logging Configuration: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'json': { 'format': '%(levelname)s %(asctime)s %(name)s %(message)s %(lineno)d %(pathname)s', 'class': 'pythonjsonlogger.jsonlogger.JsonFormatter', }, }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'json', }, }, 'loggers': { 'django': { 'handlers': ['console'], 'level': 'INFO', 'propagate': True, }, 'ru_profile': { 'handlers': ['console'], 'level': 'DEBUG', 'propagate': False, }, '': { 'handlers': ['console'], 'level': 'DEBUG', 'propagate': True, }, }, 'root': { 'handlers': ['console'], 'level': 'DEBUG', }, } Example Log Usage: import logging logger = logging.getLogger('ru_profile') class ForgotPasswordView(CreateView): model = User template_name = 'user/forgot_password.html' form_class = ForgotPasswordForm def form_valid(self, form): phone = str(form.cleaned_data['phone']) user = User.find_by_phone(phone) if user is not None: user.send_reset_pin() logger.info(f"Reset PIN sent successfully to {phone}") else: logger.error(f"Couldn't reset PIN, user not found for phone '{phone}'") django_messages.error(self.request, _("Couldn't reset your PIN. Please try again")) return self.form_invalid(form) return redirect('reset_pin_view', phone=phone) Observed Logs: In CloudWatch Logs, I only see … -
space is not sliced from my text in front-end
so here my front-end js code for the keyHandler let snippet = document.getElementById('snippet'); let remaining = document.getElementById('remaining'); let typed = document.getElementById('typed'); let result = document.getElementById('result'); const keydownHandler = (event) => { let key = event.key; if (key.length === 1 && /[a-z .]/i.test(key) ) { if (key === snippet.innerText[typed.innerText.length]) { if(key == " "){ console.log('its space !!!!!!'); typed.innerText += ' '; }else{ typed.innerText += key.toLowerCase(); } remaining.innerText = snippet.innerText.slice(typed.innerText.length); result.innerText = ''; } else { result.innerText = 'Incorrect key pressed!'; } } let message = JSON.stringify({ 'snippet_text':snippet.innerText, 'typed_text': typed.innerText, 'remaining_text': remaining.innerText, }); if (socket.readyState === WebSocket.OPEN) { console.log('Sending message:', message); socket.send(message); } }; the problem is that when i type the ' ' (spacebar) , it does not get removed from my remaining text in the front-end. here is the back-end consumer : def receive(self, text_data): data = json.loads(text_data) typed_text = data.get('typed_text', '').lower() snippet_text = data.get('snippet_text', '').lower() is_correct = typed_text == snippet_text if is_correct: self.current_snippet_index += 1 self.player_score += 1 self.send(json.dumps({ 'is_correct': is_correct, 'player_score': self.player_score, })) self.send_new_snippet() #send new snippet with full details else: remaining_text = snippet_text[len(typed_text):] self.send(json.dumps({ 'snippet_text': snippet_text, 'typed_text': typed_text, 'remaining_text': remaining_text, })) here an image of the results : -
Django app, how to generate form dynamicly based of JSON?
Currently i am doing this: [ { "name": "hostname", "type": "string", "description": "Hostname router", "required": "Yes" (No if it is not required) }, { "name": "is_dhcp", "type": "choice", "description": "DHCP?", "choices": [ [ "yes", "Yes" ], [ "no", "No" ] ], "required": "No" }, { "name": "gateway", "type": "ip", "description": "Gateway DHCP", "required": "Yes" }, { "name": "sub_int_bck", "type": "integer", "description": "In case of existing! - Sub interface", "required": "No" }, { "name": "exIpList", "type": "list", "description": "List excluded IPs, seperated by ;", "required": "No" } ] Then i use a big amount of If's to check one by one: if var_type.lower() == 'string': self.fields[var_name] = forms.CharField( label=var_description, required=var_req_bool, widget=forms.TextInput(attrs={"class": "form-control"}) ) elif var_type.lower() == 'integer': self.fields[var_name] = forms.IntegerField( label=var_description, required=var_req_bool, widget=forms.TextInput(attrs={"class": "form-control"}) ) elif var_type.lower() == 'choice': self.fields[var_name] = forms.ChoiceField( label=var_description, choices=var.get('choices', []), # Default to empty list if not provided widget=forms.Select(attrs={"class": "form-control"}), required=var_req_bool ) elif var_type.lower() == 'ip' and 'mask' in var_description.lower(): self.fields[var_name] = forms.GenericIPAddressField( label=var_description, required=var_req_bool, widget=forms.TextInput(attrs={"class": "form-control", "placeholder": "255.255.255.0 OU 0.0.0.255 OU 24"}), ) elif var_type.lower() == 'ip': self.fields[var_name] = forms.GenericIPAddressField( label=var_description, required=var_req_bool, widget=forms.TextInput(attrs={"class": "form-control", "placeholder": "192.168.1.1"}), ) elif var_type.lower() == 'list': self.fields[var_name] = forms.CharField( label=var_description, required=var_req_bool, widget=forms.Textarea(attrs={"class": "form-control"}), ) elif var_type.lower() == 'bool': self.fields[var_name] = … -
Nothing happens when transferring the registration form data to the database
I have a problem. I'm new to django. And so the error lies in the fact that nothing happens during the data transfer. The database is not being updated. I will be very grateful for your help! this is code: registration/urls.py: from django.contrib.auth import views as auth_views from django.urls import path from . import views urlpatterns = [ path('/register', views.register, name='register'), ] registration/views.py: from django.shortcuts import render from django.contrib.auth import login, authenticate from django.shortcuts import render, redirect from .forms import RegistrationForm from django.shortcuts import render, redirect def register(request): # Change function name to match the URL pattern if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): user = form.save() login(request, user) print(form) return redirect('home') else: form = RegistrationForm() return redirect('news') return render(request, 'registration/register.html', {'form':form}) urls.py(In the project itself): from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from django.contrib.auth import views as auth_views from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), path('', include('main.urls')), path('news/', include('news.urls')), path('accounts/', include('django.contrib.auth.urls')), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) register.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Регистрация</title> </head> <body> <h1>Регистрация</h1> <form method="post" action="{% url 'register' %}"> {% csrf_token %} {{ form.email }} {{ form.password1 }} {{ form.password2 … -
Django: overriding an abstract class with a generic relation limiting ContentType choices dynamically?
Following the current documentation https://docs.djangoproject.com/en/5.0/ref/contrib/contenttypes/#generic-relations I created a GenericReferModel which is an abstract class that define a generic relation towards one or more models. So far so good. Now I'd like to limit the ContentType choices exploiting the limit_choices_to attribute of models.ForeignKey. from typing import Any from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models from django.utils.translation import gettext_lazy as _ class GenericReferModel(models.Model): refer_type_choices: models.Q | dict[str, Any] | None = None # https://docs.djangoproject.com/en/5.0/ref/contrib/contenttypes/#generic-relations refer_type = models.ForeignKey( ContentType, on_delete=models.CASCADE, null=True, blank=True, limit_choices_to=refer_type_choices, verbose_name=_("refer type"), ) refer_id = models.PositiveIntegerField( _("refer id"), null=True, blank=True, ) refer = GenericForeignKey("refer_type", "refer_id") class Meta: abstract = True indexes = [ models.Index(fields=["refer_type", "refer_id"]), ] class Chat(GenericReferModel): nome = models.CharField(_("nome"), max_length=255) refer_type_choices = ( models.Q(app_label="core", model="studio") ) class Meta: verbose_name = _("chat") verbose_name_plural = _("chat") Apparently, overriding refer_type_choices does not work and it is always considered the abstract class default value. Is there a way to achieve a dynamic assignation of choices on each subclass? -
Django Custom admin template
I changed the admin site index template in Django like this: ``` admin.site.index_template = "admin/list-aprovals.html" ``` but how can i send my model datas this page or can i add a custom view for this url: ``` path('admin/', admin.site.urls), ``` So, I want to work with the existing django admin, but I only want to change the template and see my models in this special template, but with the original admin app. Is this possible in Django? How do I solve this problem? I tried custom app but i want to use original contrib admin. -
Return output of subprocess.popen() in webserver
I have a Webserver in Python using Django. I want to be able to kick of a long-running asynchronous subprocess and then have the client poll with a GET or POST and receive stdout as well as other information. For each iteration, the server will return the lines of stdout that it has so far. When the process ends, additional information will be returned. How can I save the instance of cmd=subprocess.popen() so that on subsequent GET/POST, it can make the appropriate calls (e.g. cmd.poll, cmd.stdout.readline(), etc) I've tried using Django's session manager, but the popen object is not Json serializable -
how to create a foreign key from the top model to bottom model?
class Model1(models.Model): x = models.ForeignKey(Model2, on_delete=models.CASCADE) class Model2(models.Model): y = models.CharField(max_length=200) How to create a foreign key to Model2 from Model1? I know maybe you say you just need to replace Model1 with Model2 and then create a foreign key, but sometimes like now I need to do something like this. -
how to use a variable where a keyword is expected
I have this problem with Django, but I feel is more of a python question: user_data = User.objects.filter(userid__startswith='Jeremy').values('mail','address') the above works and returns me exactly one line, as I know it should. This does not work: jeremy='Jeremy' user_data = User.objects.filter(userid__startswith=jeremy).values('mail','address') because manage.py runserver complains that my queryset is empty, when attempting to use it. I went all over the internet and found countless variations about using a dictionary, like this: my_kws={'userid__startswith':'Jeremy'} user_data = User.objects.filter(**mykws).values('mail','address') which do work, but when changed to: jeremy='Jeremy' my_kws={'userid__startswith':jeremy} user_data = User.objects.filter(**mykws).values('mail','address') absolutely do not. For me, at least, they end up exactly as before, with an empty querySet. Other uncountable answers propose to do: jeremy='Jeremy' user_data = User.objects.filter(f'userid__startswith={jeremy}').values('mail','address') with exactly the same result as before. FWIW, I am using python 3.10.12 -
Use external documentation for endpoint in Swagger UI
For a specific endpoint in our REST API I'd like to provide external documentation. There is an argument external_docs that can be passed to the extend_schema, but I haven't seen any example anywhere. I passed just the URL to the external documentation: @extend_schema_view( my_specific_endpoint=extend_schema( external_docs="https://documentation.example.com" ) ) class MySpecificViewSet(ModelViewSet): # class contents The clients should use the external documentation to get instructions on using it. This endpoint cannot be used through the Swagger UI and ideally the button "Try it out" should be disabled, if that's possible. Additionally, I'd like to disable the Parameters and the Response sections too. -
How to Detect Selected Text in a PDF Displayed in a Web Browser Using JavaScript or Python?
I'm working on a web application where users need to interact with PDF documents. Specifically, I need to detect the text that a user selects within a PDF displayed in their web browser. While I've managed to achieve this functionality with DOCX files,but converting PDFs to DOCX causes layout issues, with text alignment and images not being preserved properly. I've tried using PDF.js to render the PDF in the browser, but I'm struggling to detect the text that users select. My goal is to capture the selected text . Here are the main points I need help with: How can I detect the text that a user selects in a PDF rendered in the web browser? Is it possible to achieve this using JavaScript or Python, and if so, how? I've looked into PDF.js and tried some examples, but I haven't been successful in capturing the selected text. Any guidance, code snippets, or references to relevant libraries or techniques would be greatly appreciated. Additionally, I previously asked a similar question but using Python and django but haven't received any answers yet. Here is the link to that question for more context: text. -
Why am i facing "APPEND_SLASH" error in Django?
So i am creating a simple API sing Django. So every time i am getting the APPEND_SLASH issue while making a POST request on localhost:8000/cars from PM , in the body I am passing a JSON request body with one field based on the value of which the data is gonna be filtered from the sqlite DB. Also , i am unable to find "APPEND_SLASH" in my settings.py!! Below is the error message: RuntimeError: You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to localhost:8000/cars/ (note the trailing slash), or set APPEND_SLASH=False in your Django settings. My urls.py: from django.urls import path,include from . import views urlpatterns=[ path('cars/',views.cars,name='cars'), ] My views.py: from django.shortcuts import render from django.http import HttpResponse from cars.models import car import json from django.core import serializers from django.http import JsonResponse def cars(request): if request.method=="GET": all_cars=car.objects.all() cars_data=[] for each_car in all_cars: cars_data.append({ 'name': each_car.name, 'color': each_car.color, 'fuel': each_car.fuel }) return JsonResponse(cars_data,safe=False) elif request.method == 'POST': data=json.loads(request.body) color_of_car=data.get('color_of_car') if color_of_car is not None: one_car=car.objects.filter(color=color_of_car) output=[] for each_car in one_car: output.append({ 'name': each_car.name, 'color': … -
profile pictures for users in Django
Django has the built-in form called UserCreatioonForm for creating users. It has some fields like First and Last Name, Email, etc. But is it actually possible to have a field for uploading images which will be used as profile pictures for the user? I tried to read about additional input fields on djangoproject.com/docs, but it was rather cryptic. -
Watchtower CloudWatch Integration in Django Logs: No Log Streams Created
I have a Django project with Sentry for error tracking, and logs are stored locally on the server. I want to forward these logs to CloudWatch Logs. I am using Watchtower for this integration. Here's my settings.py: ############# LOGGING ########### from boto3 import client import watchtower logger_boto3_client = client( "logs", aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY, region_name=AWS_S3_REGION_NAME, ) LOGGING = { "version": 1, "disable_existing_loggers": False, "formatters": { "verbose": { "format": "[{levelname}] [{asctime}] [{pathname}] [{lineno}] [{message}]", "style": "{", }, }, "filters": { "debug_filter": { "()": "server_backend.log_settings.DebugFilter", }, "info_filter": { "()": "server_backend.log_settings.InfoFilter", }, "warning_filter": { "()": "server_backend.log_settings.WarningFilter", }, "error_filter": { "()": "server_backend.log_settings.ErrorFilter", }, }, "handlers": { "debug_file": { "level": "DEBUG", "class": "logging.handlers.RotatingFileHandler", "filename": f"{BASE_DIR}/logs/debug.log", "formatter": "verbose", "maxBytes": 52428800, "backupCount": 10, "filters": ["debug_filter"], }, "info_file": { "level": "INFO", "class": "logging.handlers.RotatingFileHandler", "filename": f"{BASE_DIR}/logs/info.log", "formatter": "verbose", "maxBytes": 52428800, "backupCount": 10, "filters": ["info_filter"], }, "warning_file": { "level": "WARNING", "class": "logging.handlers.RotatingFileHandler", "filename": f"{BASE_DIR}/logs/warning.log", "formatter": "verbose", "maxBytes": 52428800, "backupCount": 10, "filters": ["warning_filter"], }, "error_file": { "level": "ERROR", "class": "logging.handlers.RotatingFileHandler", "filename": f"{BASE_DIR}/logs/error.log", "maxBytes": 52428800, "backupCount": 10, "formatter": "verbose", }, "watchtower": { "level": "DEBUG", "class": "watchtower.CloudWatchLogHandler", "boto3_client": logger_boto3_client, "log_group": "server_backend", "stream_name": "{strftime:%Y-%m-%d}", "formatter": "verbose", "create_log_group": True, "create_log_stream": True, }, }, "loggers": { "server_backend": { "handlers": ["debug_file", "info_file", "warning_file", "error_file", "watchtower"], "level": "DEBUG", "propagate": True, … -
how to handel default Django authentication in forntend
I'm working on a project, in the back-end we are using Django with Rest and for front we are using Wordpress and we want to send otp for user and if the OTP code from user is valid then login the user and save the CSRF-token and so on .. but here is my problem I didn't wanted to save the opt in a table and in chatgpt it suggested that I can save it in session or memory cash, I wanted to try the session way but I encounter a problem : after calling the /send_otp/ and getting the otp I need to call the /login/ and check if the otp is a mach, but in login it returns the otp from session None and I can access the session I saved in the send_otp this is the two functions send_otp and login : class SendOTPView(APIView): def post(self, request): serializer = OTPSerializer(data=request.data) if serializer.is_valid(): phone_number = serializer.validated_data["phone"] otp_code = randint(100000, 999999) request.session['otp_code'] = otp_code print("otp in sendOTP",request.session.get("otp_code")) otp_send(phone_number, otp_code) return Response( {"detail": "OTP sent successfully"}, status=status.HTTP_200_OK ) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class UserLoginView(APIView): def post(self, request): serializer = UserLoginSerializer(data=request.data) if serializer.is_valid(): stored_otp = request.session.get("otp_code") print(stored_otp) user_entered_otp = serializer.validated_data["otp"] phone_number = … -
Cpanel Cron Job not working for everyday day
Cpanel Cron jobs Images I have 3 cron jobs in my cpanel, I am hitting APIs with curl, my hourly cron job is working fine but Daily cron job is not, monthly is not get to test yet for cron: you might think there is some error with API, so heres the deal: I edited the same API and changed its time to minute, the cron job starts working started wokring When i hit the API with postman manually it wokrs also i put the curl command that i put in cron into the live terminal of ssh, it works It is so weird but I am now irritated, Any Help? -
Django trying to encrypt fields when creating database and retrieveing them in decrypted form, how can I achieve this?
I am working on a django project where I need to store data inside some columns in an encrypted format and decrypt it on the fly whenever querying the said data. I have managed to encrypt the data while storing using cryptography-Fernet. def save(self, *args, **kwargs): if isinstance(self.first_name, str): self.first_name = cipher_suite.encrypt(self.first_name.encode()) super().save(*args, **kwargs) but When I am trying to retrieve the data, I am not able to fetch it in a decrypted format, As I do not know which method to override to achieve this result. What can I do to make this work? I have tried creating a property at django model But I am unable to trigger it, as I am not aware on how to trigger a model property in django models when a queryset is being executed. This is the property in question. @property def enc_first_name(self): if self.first_name: val = cipher_suite.decrypt(self.first_name).decode() return val return self.first_name Alternate solutions I tried, because our project is on python 3.10 and django 5.0, I am unable to use django-cryptography library which would have reduced complexity of this task tremendously. Also I have been recommended to use microsoft-presidio library but that only seems to work on text data directly. I … -
How to import a folder into postman?
Shows an error "No supported files found for import." I was trying to import my django folder into postman to test api's. Firstly I tried to do it in the postman app and then i installed postman extension from the vs code, the result was same. -
Django connect to remote Postgres: '127.0.0.1 works while 'localhost' fails
I set up local port forwarding to remote server on which a Postgres db is running. ssh -v -L 127.0.0.1:5433:localhost:5432 user@server-ip I can't connect from my django local server if host is set to localhost but it works if replaced by 127.0.0.1 My django settings: # settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': '<db_name>', 'USER': '<db_user>', 'PASSWORD': 'django', 'HOST': 'localhost', 'PORT': '5433', } } When I run server, I got error as below: Error occurred during checks: OperationalError('connection failed: :1), port 5433 failed: could not receive data from server: Connection refused\ncould not send startup packet: Connection refused') I wanted to identify if the connection issue comes from client or server side, so I tried to connect to the db by psql: psql <db_name> -U <db_user> -p 5433 -h localhost and it works !!! So I guessed it was client issue. The django server could only connect to the db only when I changed 'HOST': 'localhost' to 'HOST': '127.0.0.1' My /etc/hosts: 127.0.0.1 localhost 255.255.255.255 broadcasthost ::1 localhost 127.0.0.1 postgres 127.0.0.1 mysql 127.0.0.1 redis pg_hba.conf: 127.0.0.1 localhost 255.255.255.255 broadcasthost ::1 localhost # Added by saritasa 127.0.0.1 postgres 127.0.0.1 mysql 127.0.0.1 redis # Added by Docker Desktop # To allow the … -
Issue accessing deeply nested attributes in Django Rest Framework serializer's validate method
I'm facing an issue while trying to access deeply nested attributes within the validate method of a Django Rest Framework serializer. Here's a simplified version of my serializer: from rest_framework import serializers from myapp.models import User class YourSerializer(serializers.ModelSerializer): def validate(self, attrs): if hasattr(self.parent.instance, 'vehicle'): if hasattr(self.parent.instance.vehicle, 'engine'): if hasattr(self.parent.instance.vehicle.engine, 'fuel'): fuel_type = self.parent.instance.vehicle.engine.fuel.diesel if fuel_type: pass else: raise serializers.ValidationError("Fuel type is not available.") else: raise serializers.ValidationError("Fuel attribute is not available.") else: raise serializers.ValidationError("Engine attribute is not available.") else: raise serializers.ValidationError("Vehicle attribute is not available.") return attrs In the validate method, I'm attempting to access deeply nested attributes (vehicle.engine.fuel.diesel) of the parent instance. The thing is Model engine is created after user does ABC operations, and same applies for fuel, and diesel. When a load of people work on codebase its tough to identify if a these Models are created or not, normally getattr() and hasattr() are used, but clubbing these a lot makes code look messy. Tried static loots like mypy and pylint, they help to a certain extent but sometimes, TypeError, NoneType issues popup. Not sure how to fix these. Thank you for your help! -
Django can't find leaflet admin widget.html
I want to use LeafletGeoAdmin in the Admin pages. from leaflet.admin import LeafletGeoAdmin @admin.register(Marker) class MarkerAdmin(LeafletGeoAdmin): list_display = ("name", "location") When I try to add a marker, I get the error: TemplateDoesNotExist at /admin/my_app/marker/add/ Exception Value: leaflet/admin/widget.html Django tried loading these templates, in this order: django.template.loaders.filesystem.Loader: /home/me/my_map/.venv/lib/python3.10/site-packages/django/forms/templates/leaflet/admin/widget.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/me/my_map/my_map/templates/leaflet/admin/widget.html (Source does not exist) ... etc ... So it's looking for widget.html in paths of the form <many-places>/leaflet/admin/widget.html. None of the places it's looking in has it. By looking in .venv I did find it at /home/me/my_map/.venv/lib/python3.10/site-packages/leaflet/templates/leaflet/admin/widget.html instead of at site-packages/django/forms/templates/, etc. So I added that templates/ location with both absolute and relative paths to settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'my_app','templates'), '/home/me/my_map/.venv/lib/python3.10/site-packages/leaflet/templates/', os.path.join(BASE_DIR,'.venv/lib/python3.10/site-packages/leaflet/templates/') ], ... But it still gives me the same error. why does django-leaflet not know the right path, and 2) why can't Django find it at the template path I specified? -
How can I serve React Frontend and Django Backend on IIS?
Background We have an application using React.js for the frontend and Django for the backend. We are attempting to deploy this application on an Azure virtual machine with IIS. Problems Encountered Backend Accessibility: We are uncertain whether our Django server is running and how to access it. Accessing localhost only serves the frontend, raising concerns about frontend-backend communication. 404 Error on Page Refresh: When navigating to authentication/sign-in from the frontend, it works fine. However, refreshing this page results in a HTTP Error 404.0 - Not Found error. It seems IIS is looking for a physical path that doesn't exist, as the build folder contains only static files (CSS, JS, etc.). Steps Taken Created a new instance on Azure: Installed Python and other necessary packages. Configured IIS: Enabled IIS features and other relevant features. Installed SSL certificate (.pfx) using MMC to enable HTTPS support. Moved project folder to C:\inetpub\wwwroot. Configured the Python path and FastCGI path in the web.config file, placed next to the project folder. Setup Virtual Directory: Moved the build folder (static build from React) to the virtual directory. Completed all configurations for mapping, FastCGI, and static file handling. Running the Application: The frontend is served successfully when accessed … -
Django User object has no attribute user
I am trying to create some custom authentication classes to check if the request user is part of certain groups or not. However, I am getting this AttributeError: 'User' object has no attribute 'user' appear and I dont know how to resolve it. This is the file I created for my custom authentication classes: from rest_framework import permissions class IsManager(permissions.BasePermission): def has_permission(self, request, view): if request.user.user.group.filter(name='managers').exists(): return True else: return False class IsDeliveryCrew(permissions.BasePermission): def has_permission(self, request, view): if request.user.user.group.filter(name='delivery crew').exists(): return True else: return False This is me view file: from rest_framework import generics, status from rest_framework.permissions import IsAuthenticated, IsAdminUser from rest_framework.response import Response from rest_framework.throttling import AnonRateThrottle, UserRateThrottle from django.shortcuts import get_object_or_404 from django.http import HttpResponseBadRequest from django.contrib.auth.models import Group, User from .models import Category, MenuItem, Cart, Order, OrderItem from .serializers import CategorySerialzier,MenuItemSerialzier,CartHelpSerializer, CartAddSerialzier,CartRemoveSerializer, CartSerialzier, ManagerListSerializer,OrderSerialzier,OrderItemSerializer,OrderAddSerializer, OrderItemHelperSerialzier from .permissions import IsManager, IsDeliveryCrew from datetime import date import math class CategoriesView(generics.ListCreateAPIView): throttle_classes=[UserRateThrottle,AnonRateThrottle] queryset = Category.objects.all() serializer_class = CategorySerialzier permission_classes= [IsAdminUser] class MenuItemsView(generics.ListCreateAPIView): throttle_classes=[UserRateThrottle,AnonRateThrottle] queryset = MenuItem.objects.all() serializer_class = MenuItemSerialzier search_fields = ['title','category__title'] ordering_fields = ['price','category'] def get_permissions(self): permission_classes = [] if self.request.method != 'GET': permission_classes = [IsAuthenticated,IsAdminUser] return [permission() for permission in permission_classes] class SingleMenuItemView(generics.RetrieveUpdateDestroyAPIView): throttle_classes=[UserRateThrottle,AnonRateThrottle] queryset = MenuItem.objects.all() serializer_class …