Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Image upload corruption with SeaweedFS S3 API
Problem Description I'm experiencing an issue where images uploaded through Django (using boto3) to SeaweedFS's S3 API are corrupted, while uploads through S3 Browser desktop app work correctly. The uploaded files are 55 bytes larger than the original and contain a Content-Encoding: aws-chunked header, making the images unopenable. Environment Setup Storage: SeaweedFS with S3 API Proxy: nginx (handling SSL) Framework: Django Storage Client: boto3 Upload Method: Using Django's storage backend with PrivateStorage Issue Details When uploading through S3 Browser desktop app: File size matches original Image opens correctly No corruption issues When uploading through Django/boto3: File size increases by 55 bytes Response includes Content-Encoding: aws-chunked Image becomes corrupted and unopenable First bytes contain unexpected data (100000) Last bytes end with .x-amz-checksum- Example of Corrupted File Original file size: 12345 bytes Uploaded file size: 12400 bytes (+55 bytes) First bytes: 100000... Last bytes: ...x-amz-checksum-crc32:SJJ2UA== Attempted Solutions Tried different upload methods: # Method 1: Using ContentFile storage.save(path, ContentFile(file_content)) # Method 2: Using Django File object storage.save(path, File(file)) # Method 3: Direct boto3 upload client.upload_fileobj(f, bucket_name, path) Questions Is this a known issue with SeaweedFS's S3 API implementation? Is there a way to disable the aws-chunked encoding in boto3? Are there specific headers … -
How to avoid redundant manual assignment of environment variables in Django settings?
In my Django project, I store configuration variables in a .env file for security and flexibility. However, every time I introduce a new environment variable, I have to define it in two places: .env and settings.py. As the project grows and the number of environment variables increases, settings.py gets cluttered with redundant redefinitions of what’s already in .env. Is there a way to automatically load all .env variables into Django’s settings without manually reassigning each one? Ideally, I want any new variable added to .env to be instantly available from settings module without extra code. What I can think of is something like: from dotenv import dotenv_values env_variables = dotenv_values(".envs") globals().update(env_variables) Or even something a little bit better to handle values of type list. for key, value in env_variables.items(): globals()[key] = value.split(",") if "," in value else value # Ensure ALLOWED_HOSTS is always a list ALLOWED_HOSTS = ALLOWED_HOSTS if isinstance(ALLOWED_HOSTS, list) else [ALLOWED_HOSTS] But I do not like to mess around with globals(). -
Django app performance issues with cloud PostgreSQL & Redis
I recently deployed my Django app on Railway, where I set up PostgreSQL and Redis and connected them to my project. However, I’ve noticed a drastic slowdown in query and cache performance compared to running locally—by several orders of magnitude. For example, one of my views executes queries in 2.58ms on my local database but takes 7411.42ms on Railway. Similarly, the same view’s cache time is 24.14ms on local Redis but 2122.14ms on Railway. I expected some performance drop when moving to a cloud-hosted setup, but this level of slowdown seems excessive. Initially, I suspected an incorrect connection setup on Railway, but after testing with Redis Cloud, the performance remained similar to Railway’s Redis. I haven’t tested another cloud database yet. Does anyone have insights into what might be causing such a drastic difference? Here’s my database setup in settings.py: DATABASES = { 'default': dj_database_url.config(default=os.getenv('DATABASE_URL')) } and cache setup: SESSION_ENGINE = "django.contrib.sessions.backends.cache" SESSION_CACHE_ALIAS = "default" SELECT2_CACHE_BACKEND = "select2" CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": REDIS_URL, "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } }, 'select2': { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": REDIS_URL, "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } } } Any help would be greatly appreciated! Thanks! -
How to fix "SignUpView is missing a QuerySet"
In my django web app i am trying to build a Newspaper app, in my homepage when i click on SIGN UP Button i get an error "ImproperlyConfigured at /accounts/signup/", I didnt figure out where is the problem. forms.py: from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser class CustomUserCreationForm(UserCreationForm): #Creation of CustomUser class Meta: model = CustomUser fields = UserCreationForm.Meta.fields + ("age",) class CustomUserChangeForm(UserChangeForm): #Modifying existing users class Meta: model = CustomUser fields = UserChangeForm.Meta.fields and models.py: from django.contrib.auth.models import AbstractUser #username, pw1, pw2 from django.db import models class CustomUser(AbstractUser): age = models.PositiveIntegerField(null=True, blank=True) urls.py: from django.urls import path from .views import SignUpView #Accounts/urls.py : Handles only registrations URLs!! urlpatterns = [ path('signup/', SignUpView.as_view(), name='signup'), ] and views.py: from django.urls import reverse_lazy from django.views.generic import CreateView from .forms import CustomUserCreationForm class SignUpView(CreateView): from_class = CustomUserCreationForm success_url = reverse_lazy('login') template_name = 'registration/signup.html' signup.html: {% extends 'base.html' %} {% block title %}Sign Up{% endblock title %} {% block content %} <h2>Sign Up</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Sign Up</button> </form> {% endblock content %} I tried to change fields in forms.py with: fields = ( "username", "email", "age",) but nothing to be mention -
Why does my code execute despite error message?
I have Created a react app the allows me to enter form data and send it to my django backend. I also have created a delete view that will trigger when the request containe the "DELETE" phrase. I noticed that after sending a request which included the line of code below, I received a PUT 400 error on my browser as well as in the django console. However, the delete request was still executed. Kindly assist as i am confused about why the request still executed tho i got an error. formData.append("drivers_license", "DELETE"); -
How to properly connect PostgreSQL with Django?
I'm working on a Django project and using PostgreSQL as my database. I updated my settings.py as follows: ** DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'mydatabase', 'USER': 'myuser', 'PASSWORD': 'mypassword', 'HOST': 'localhost', 'PORT': '5432', } } ** However, when I run python manage.py migrate, I get the following error: django.db.utils.OperationalError: could not connect to server: Connection refused I have PostgreSQL installed and running. I also verified that my credentials are correct. What could be the issue? -
Django ManyToMany Relationship Not Returning First Available Size in View
I am working on a Django e-commerce project where a product can have multiple sizes. However, I am facing an issue where, if no size is explicitly selected by the user, the system should automatically take the first available size of the product. Currently, it always returns "No Size", even though sizes exist for the product. Models: Here is my Product model: class Product(models.Model): pid = ShortUUIDField(length=10, max_length=100, prefix="prd", alphabet="abcdef") title = models.CharField(max_length=100, default="Apple") image = models.ImageField(upload_to=user_directory_path, default="product.jpg") price = models.DecimalField(max_digits=10, decimal_places=2, default=1.99) old_price = models.DecimalField(max_digits=10, decimal_places=2, default=2.99) size = models.ManyToManyField("Size", blank=True) def get_product_price_by_size(self): """Returns price based on the first available size if none is selected""" first_size = self.size.first() # Get the first available size if first_size: return self.price + first_size.price # Assuming 'price' exists in Size model return self.price # Default to base price if no size exists def __str__(self): return self.title class Size(models.Model): name = models.CharField(max_length=100) price = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) def __str__(self): return self.name View Handling "Add to Cart" (add_to_cart_search): When a user clicks "Add to Cart," I want to fetch the product's size. If no size is explicitly selected, the first available size should be assigned automatically. def add_to_cart_search(request): if request.GET.get('buy_now'): return redirect('core:payment_getway') product_id = request.GET.get('pid') … -
Trouble setting PORT in Django/Heroku Procfile using Waitress
I'm trying to deploy my Django application with Heroku (on Windows), and using Waitress (because Gunicorn no longer runs on Windows??). When I hard coded the PORT number, I was able to run it fine. When I try to define PORT in the Procfile as an environment variable Procfile: web: waitress-serve --port=$PORT [projectname].wsgi:application .env WEB_CONCURRENCY=2 PORT=$PORT settings.py import environ from environ import Env ... PORT = env('PORT') running "heroku local" produces ValueError: invalid literal for int() with base 10: '$PORT' I keep seeing mention that "$PORT" is not appropriate for Windows. However I can't figure out what I'm missing. I've seen suggestions that "%PORT%" would work for Windows, but I haven't had success. If there is a Windows friendly syntax, would I need to use it in both .env and Procfile? -
uploading multiple images in Django admin
I have a category and for each category I want to add multiple images but whatever I do, I have just one upload file but I want to have multiple. In my Django project I have this class: in my model file: class SalonSampleImages(models.Model): service = models.ForeignKey(Salon, on_delete=models.CASCADE) Category = models.ForeignKey( ServiceCategory, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="the main service", default=1 ) image = models.ImageField(upload_to='salon_images/', verbose_name="images") def __str__(self): return f"images" class Meta: verbose_name = "picture" verbose_name_plural = "pictures" in my admin file: class SalonSampleImagesInLineFormSet(forms.BaseInlineFormSet): def clean(self): super().clean() total_images = len([form for form in self.forms if form.cleaned_data and not form.cleaned_data.get('DELETE', False)]) if total_images < 3: raise ValidationError("you must all at least 3 images") if total_images > 10: raise ValidationError("you cannot add more than 10 images") class SalonSampleImagesInLine(admin.TabularInline): model = SalonSampleImages formset = SalonSampleImagesInLineFormSet extra = 1 and I registered all then I created a model file: class MultiFileInput(forms.ClearableFileInput): allow_multiple_selected = True def __init__(self, attrs=None): if attrs is None: attrs = {} attrs.setdefault('multiple', 'multiple') super().__init__(attrs=attrs) def value_from_datadict(self, data, files, name): return files.getlist(name) class MultiImageUploadForm(forms.Form): category = forms.ModelChoiceField( queryset=ServiceCategory.objects.all(), label="choose category" ) images = forms.FileField( widget=MultiFileInput(), label="upload pictures" ) then I created a html file: {% extends "admin/base_site.html" %} {% block content %} <h1>{{ title … -
Django app works locally but shows "Unhandled Exception" on PythonAnywhere (Logs available)
Link to the youtube video: https://youtu.be/iJrUiem10iI I have developed a Django application that includes features like downloading YouTube videos (using yt-dlp) and potentially converting file formats. The Problem: The application runs perfectly fine on my local machine using python manage.py runserver. I can access the views, for example at http://127.0.0.1:8000/converter/, and the functionality works as expected. However, after deploying the application to PythonAnywhere (using the free tier), I encounter an error. When I try to access my site at https://kristjan.pythonanywhere.com/ or the specific app URL https://kristjan.pythonanywhere.com/converter/, I get a generic PythonAnywhere error page stating: Something went wrong :-( Something went wrong while trying to load this website; please try again later. Error code: Unhandled Exception Self-note: The error page provides links to logs, which should contain the specific traceback. What I've Done and Checked: Local Server: Confirmed the app works correctly locally via runserver. The URL http://127.0.0.1:8000/converter/ loads the correct index.html template. Virtual Environment: Created a virtualenv on PythonAnywhere at /home/Kristjan/.virtualenvs/djangoappvirtualenv. I activated this virtualenv and installed all necessary packages (Django, yt-dlp, etc., matching my local environment as closely as possible) using pip install -r requirements.txt (or individually) within a PythonAnywhere console. Database Setup: Configured the default DATABASES setting in … -
password reset email in django
ive been following along with corey schafers django blog app tutorial on youtube, and up until episode 12 everything was fine and perfect. But i cant make the password reset email work no matter what i try i have all the code exactly how he does and i think what it might be is google app password but i have no idea how to link it to the application. if anyone can help it would be much appreciated! path('password-reset/', auth_views.PasswordResetView.as_view(template_name='users/password_reset.html'), name='password_reset'), path('password-reset/done/', auth_views.PasswordResetDoneView.as_view(template_name='users/password_reset_done.html'), name='password_reset_done'), path('password_reset_confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name='users/password_reset_confirm.html'), name='password_reset_confirm'), EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = os.environ.get('EMAIL_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASS') -
Why do filters affect the result of StringAgg?
I'm using StringAgg and order as follows: # Get order column & annotate with list of credits if request.POST.get('order[0][name]'): order = request.POST['order[0][name]'] if order == 'credits_primary': releases = releases.annotate(credits_primary=StringAgg( 'credits__entity__name', delimiter=', ', filter=Q(credits__type='primary'), ordering='credits__id' )) elif order == 'credits_secondary': releases = releases.annotate(credits_secondary=StringAgg( 'credits__entity__name', delimiter=', ', filter=Q(credits__type='secondary'), ordering='credits__id' )) else: order = 'title' # Order releases if request.POST.get('order[0][dir]') == 'desc': releases = releases.order_by(F(order).desc(nulls_last=True), 'title') else: releases = releases.order_by(F(order).asc(nulls_last=True), 'title') for release in releases: try: print(release.credits_primary) except: pass try: print(release.credits_secondary) except: pass This in itself works exactly as expected: the ordering is what I expect, and print returns the values I expect. However, when I apply filters before this, it starts behaving strangely. Namely, sometimes it's fine and still works as expected, sometimes each credits__entity__name is repeated a random number of times, sometimes the annotation just returns None even though there are values. I can't figure out a pattern here. Below are the filters I'm applying, note that exclude as far as I can tell does not cause this problem: if request.POST.get('entity'): releases = Release.objects.filter(credits__entity=request.POST['entity']) else: releases = Release.objects.all() records_total = releases.count() # Filter by type if request.POST.get('type'): query = Q() for type in loads(request.POST['type']): if type in Release.TYPES_P_TO_S: query.add(Q(type=Release.TYPES_P_TO_S[type]), Q.OR) releases … -
Why is the data-tags attribute not preserved in my Django form widget? autoComplete DAL Select2
I'm using a CharField with a custom widget (ListSelect2) from the django-autocomplete-light library. I have a set of data-* attributes, including data-tags, that I want to be passed to the HTML output, but it doesn't seem like the data-tags attribute is being preserved or rendered correctly in the final after form is saved. industry_type = forms.CharField( widget=autocomplete.ListSelect2( url='/career-listings/industry-autocomplete/', attrs={ 'class': 'w-full px-4 py-2 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition duration-200', 'data-placeholder': 'Industry', 'data-minimum-input-length': 1, 'data-theme': 'tailwindcss-3', 'data-tags': 'true', # The attribute I'm trying to preserve 'id': 'id_industry_type', }, forward=['name'], ), required=True, ) What happens instead: The data-tags attribute does not appear in the HTML after form is saved. The field Things I've tried: I added data-tags to the attrs dictionary of the widget. I ensured that the widget is being properly rendered in the template. The data only data-tags is not preserved on form is submitted. -
Getting list of distinct ManyToManyField objects
Given these models: class Format(models.Model): name = models.CharField(unique=True) # More fields... class Release(models.Model): formats = models.ManyToManyField(Format, blank=True) # More fields... When I have a queryset of Releases (e.g. through releases = Release.objects.filter(foo='bar')), how do I get a list of the formats in that queryset, as objects and distinct? Neither of the following achieve this: # produces a list of dicts with IDs, not distinct e.g. [ { 'formats': 1 }, { 'formats': 2 }, { 'formats': 1 } ]: formats = releases.values('formats') # produces a list of IDs, not distinct, e.g. [ 1, 2, 1 ]: formats = releases.aggregate(arr=ArrayAgg('platforms'))['arr'] The only way I can think of is manually creating a list by looping through the IDs, checking if it already exists in the list, and if not adding it with formats.append(Format.objects.get(id=the_id)), but I would really like to avoid doing that, if possible. -
(fields.E331) Field specifies a many-to-many relation through model, which has not been installed
When I run makemigrations I get the error teams.Team.members: (fields.E331) Field specifies a many-to-many relation through model 'TeamMember', which has not been installed. from django.db import models from django.conf import settings from common import TimestampMixin from users.models import User class Team(models.Model, TimestampMixin): name = models.CharField(max_length=100) owner = models.ForeignKey( User, related_name='owned_teams', on_delete=models.CASCADE ) members = models.ManyToManyField( User, through='TeamMember', related_name='teams' ) def __str__(self): return self.name class TeamMember(models.Model, TimestampMixin): user = models.ForeignKey( User, on_delete=models.CASCADE ) team = models.ForeignKey( Team, on_delete=models.CASCADE ) def __str__(self): return f"{self.user} in {self.team}" I don't get why it's happening because the 'teams' app is installed and both Team and TeamMember is in the same file. Any ideas? -
Getting error message running Django server
I’m not able to run python manage.py runserver. I was able to run python manage.py migrate successfully. I even changed ASGI_APPLICATION = "MyProject.asgi.application" to ASGI_APPLICATION = "routing.application" which didn’t work. Here is the error I get show_sunset_warning() System check identified no issues (0 silenced). March 28, 2025 - 17:51:56 Django version 5.1.7, using settings 'MyProject.settings' Starting ASGI/Daphne version 4.1.2 development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Exception in thread django-main-thread: Traceback (most recent call last): File "/home/corey-james/Arborhub/MyProject/venv/lib/python3.12/site-packages/daphne/management/commands/runserver.py", line 29, in get_default_application module = importlib.import_module(path) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/lib/python3.12/importlib/__init__.py", line 90, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1387, in _gcd_import File "<frozen importlib._bootstrap>", line 1360, in _find_and_load File "<frozen importlib._bootstrap>", line 1331, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 935, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 995, in exec_module File "<frozen importlib._bootstrap>", line 488, in _call_with_frames_removed File "/home/corey-james/Arborhub/MyProject/MyProject/asgi.py", line 12, in <module> import arborchat.routing File "/home/corey-james/Arborhub/MyProject/arborchat/routing.py", line 3, in <module> from . import consumers File "/home/corey-james/Arborhub/MyProject/arborchat/consumers.py", line 2, in <module> from channels.exceptions import StopConsumer ImportError: cannot import name 'StopConsumer' from 'channels.exceptions' (/home/corey-james/Arborhub/MyProject/venv/lib/python3.12/site-packages/channels/exceptions.py) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3.12/threading.py", line 1075, in _bootstrap_inner self.run() File "/usr/lib/python3.12/threading.py", line … -
why does the terminal say PATCH but no change in database
in my webpage, i update the request details to approve or reject. but it does not change in the status and still shows pending. the problem is, in my terminal it says PATCH so I though that means change and the database has been changed. but when I run my SQL shell, it still shows pending . what would the problem be? this is my handlestatusupdate code in the frontend: **const handleStatusUpdate = async (newStatus: 'approved' | 'rejected') => { if (!selectedRequest?.id) return; try { const response = await fetch(`${API_URL}/requests/${selectedRequest.id}/`, { method: 'PATCH', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ status: newStatus }), }); if (!response.ok) { throw new Error('Failed to update request status'); } const updatedRequest = await response.json(); setRequests(requests.map(req => req.id === selectedRequest.id ? updatedRequest : req )); setShowModal(false); } catch (err: any) { setError(err.message || 'Failed to update status'); } }; ** what other code would i need to share? the backend? -
How to create django site variables (NOT constants)?
I need to add a variable to Django. Important detail: I need a variable, not a constant, so simply adding it to settings.py is not an option. It is highly desirable to be able to change its value from the site admin panel. What is the most Django way to do this? -
How to run Django migrations in Visual Studio 2022
I have created a Django project in my Visual Studio solution. The db.sqlite3 file was also created. There are a few classes in models.py. class Question(models.Model): q_id = models.IntegerField() text = models.CharField(max_length=500) class Option(): option_num = models.IntegerField() text = models.CharField(max_length=1000) When I right click on the project, there are these options - Make Migrations, Migrate & Create Superuser. When I execute Django Make Migrations, in the terminal it says Executing manage.py makemigrations, but nothing happens. Then I execute Migrate. It says, a command is already running. The __init__.py isn't updated. I also tried, executing this command in VS Terminal, but there is no response. python manage.py makemigrations -
How can I implement jaeger with django project to view traces in grafana?
I have a legacy django project in python 2 where I needed to implement jaeger in it. How can I do that, Can anyone guide me on the same? python 2.7 django-1.11.1 -
Is it possible to use python-social-auth's EmailAuth with drf-social-oauth2 for registration
I have a facebook authentication in my project, and I've set up some pipelines. So It would be nice for non-social email registration to also utilize these pipelines. I tried adding EmailAuth to the authentication backends list, but I don't know what view to use now for registratioin. So, is it possible (or reasonable) to use EmailAuth with drf-social-oauth2 for non-social registration, and if so, how do I do it? -
Django Search Query Vulnerable to XSS - How to Prevent It?
I am working on a Django search functionality, and I noticed that when I pass JavaScript code in the URL query parameter, it executes on the page. Problem When I enter the following URL in my browser: http://127.0.0.1:8000/search/?q=%3Cscript%3Ealert(%27Hacked!%27)%3C/script%3E it shows an alert box with "Hacked!". I suspect my site is vulnerable to Reflected XSS. views.py from django.shortcuts import render def search_view(request): q = request.GET.get("q", "") # Get query parameter return render(request, "search.html", {"q": q}) search.html <h1>Search Results for: {{ q }}</h1> <!-- Displays the search query --> If I enter <script>alert('Hacked!')</script> in the search box, the JavaScript executes on the page instead of being displayed as plain text. What I Need Help With Why is this happening? What is the correct way to prevent XSS in this case? Does Django provide a built-in security mechanism for this? I appreciate any guidance on securing my search functionality. -
here i have some models and its linked with other models. each model is dependant with other model but now its not depending
[enter image description here][1][here before selecting sub department i have to select main department and sub comes under main department.][2] [1]: https://i.sstatic.net/3GSQjtkl.png [2]: https://i.sstatic.net/Tp9kg2uJ.png these are the models. models.py class Department(models.Model): department_name = models.CharField(max_length=255) # ✅ Correct field company_name = models.ForeignKey(CompanyName, on_delete=models.CASCADE) status = models.CharField(max_length=20, choices=[('active', 'Active'), ('inactive', 'Inactive')]) def __str__(self): return self.department_name class SubDepartment(models.Model): sub_department_name=models.CharField(max_length=100,null=False,blank=False) department_name=models.ForeignKey(Department,on_delete=models.CASCADE) company_name=models.ForeignKey(CompanyName,on_delete=models.CASCADE) status=models.CharField(max_length=20, choices=[('active','Active'),('inactive','Inactive')]) def __str__(self): should i make any change in forms or views? forms.py class DepartmentForm(forms.ModelForm): class Meta: model = Department fields = ['department_name', 'company_name', 'status'] class SubDepartmentForm(forms.ModelForm): class Meta: model = SubDepartment fields = ['sub_department_name', 'department_name', 'company_name', 'status'] i already give one to many into the fields but its not working as dependant. here when i select the department the corresponding sub department only should come but without selecting the dept the sub department is listing. **views.py** def dept_view(request): if request.method == "POST": form = DepartmentForm(request.POST) if form.is_valid(): form.save() return redirect('department-view') else: form = DepartmentForm() depts = Department.objects.all() return render(request, "dept.html", {"form": form, "depts": depts}) # @login_required(login_url="signin") def delete_department(request, department_id): if request.method == "POST": department = get_object_or_404(Department, id=department_id) department.delete() return JsonResponse({"success": True}) return JsonResponse({"success": False}) def sub_dept_view(request): if request.method == "POST": form = SubDepartmentForm(request.POST) if form.is_valid(): form.save() return redirect("sub-department") # Redirect … -
fieldsets(legend) in modelform django
I have a model form forms.py class (forms.ModelForm): class Meta: model = InfoPersonal fields = [ 'name', 'phone_number' ] models.py class InfoPersonal(models.Model): name = models.CharField(_('Имя'), max_length=50) phone_number = PhoneNumberField( _('Номер телефона'), max_length=20, unique=True, blank=True, null=True, personal_info-add.html <form enctype="multipart/form-data" action="{% url 'workflows:personal_info-add' user.pk %}" method="post"> {% include "_parts/form.html" with form=form %} </form> I want to get the result as shown in the picture( email -> name passord -> tel). Is it possible to add a tag in the module itself? I need the <name> and <phone_number> fields to be inside the tag <fieldset> (legend)enter image description here how to implement it help please!!! -
Google Calendar API on EC2 (AWS) - webbrowser.Error: could not locate runnable browser
I am developing a Django App where a user can access his Google Calendar using this script credentials = None token = os.path.join(folder, "token.pickle") if os.path.exists(token): with open(token, 'rb') as tk: credentials = pickle.load(tk) if not credentials or not credentials.valid: if credentials and credentials.expired and credentials.refresh_token: credentials.refresh(Request()) else: credentials = os.path.join(folder, "credentials.json") flow = InstalledAppFlow.from_client_secrets_file( credentials, scopes=['openid', 'https://www.googleapis.com/auth/calendar'] ) flow.authorization_url( # Recommended, enable offline access so that you can refresh an access token without # re-prompting the user for permission. Recommended for web server apps. access_type='offline', # Optional, enable incremental authorization. Recommended as a best practice. include_granted_scopes='true', # # Optional, if your application knows which user is trying to authenticate, it can use this # # parameter to provide a hint to the Google Authentication Server. login_hint=useremail, # Optional, set prompt to 'consent' will prompt the user for consent prompt='consent') flow.run_local_server() credentials = flow.credentials with open(token, 'wb') as tk: pickle.dump(credentials, tk) service = build('calendar', 'v3', credentials = credentials) When I test it on my local machine everything works fine. However, I run it on a EC2 instance on AWS I get this error: flow.run_local_server() File "/home/ubuntu/webapp/lib/python3.12/site-packages/google_auth_oauthlib/flow.py", line 447, in run_local_server webbrowser.get(browser).open(auth_url, new=1, autoraise=True) ^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/lib/python3.12/webbrowser.py", line 66, in get …