Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to prevent duplicate requests in apache2
I am having an issue with an Apache2 web server. I had a site working for a while, but now every request that is sent to the server has a duplicate and the first request isn't visible to the user at all. I am able to temporarily patch this by using database transactions to only return a response on the second request, with Django middleware, but the software still shows duplicate requests in the logs, each GET and POST request sent to the server has a duplicate counterpart. I have tried a suggestion I found, using modsecurity2, but it doesn't seem to work, it still lets duplicate requests through. The solution is below. SecRule USER:duplicaterequest "@gt 1" "id:'40000',phase:2,deny,status:409,msg:'Duplicate Request!'" The requests are about 2 seconds apart, and this causes all sorts of issues with duplicate objects and also seems to make the pages take longer to load. This happened overnight several weeks ago without any changes to the code. Any idea what this could be, or a way to fix it? -
Django GraphQL Endpoint Not Found When Requested via Krakend API Gateway
Hello StackOverflow Community, I am currently experiencing an issue with a Django project using GraphQL, specifically when attempting to access the GraphQL endpoint through the Krakend API Gateway. Environment: Django: 4.2.6 GraphQL Krakend API Gateway Dockerized environment Problem: When I send a request directly to the Django backend's /graphql endpoint, it works as expected. However, when I attempt to access the same endpoint via the Krakend API Gateway, I receive a 404 Not Found error. Error Log: Here is the error message received in the Docker logs: backend_1 | Not Found: /graphql backend_1 | [14/Oct/2023 23:32:52] "POST /graphql HTTP/1.1" 404 2961 This indicates that when the request is routed through Krakend to the Django backend, the /graphql endpoint cannot be found. Code: In my urls.py, I have the /graphql endpoint defined as: from django.urls import path, re_path from graphene_django.views import GraphQLView from django.views.decorators.csrf import csrf_exempt urlpatterns = [ path('graphql/', csrf_exempt(GraphQLView.as_view(graphiql=True, name='graphql'))), # ... other paths ... ] My settings (pertinent to the URLs and middleware) in settings.py include: ALLOWED_HOSTS = ['backend', 'frontend', 'localhost', ...] INSTALLED_APPS = ['graphene_django', ...] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_WHITELIST = ["http://localhost:3000"] Attempted Solutions: Verified the /graphql endpoint is … -
Handing foreign keys relations with Django's rest framework?
Description: I am creating a Django application for the first time and using the rest framework. My goal is to use the rest framework to test a post request for creating a new "Artwork" and adding it to my database. An artwork contains columns such as title, width, height, and etc. It also contains a column for a foreign key called "artist_id". This foreign key is linked to the primary key of my "Artist" table. In my artist table, I have the an artist_name column. My "Artwork" and "Artist" tables in Models.py: class Artwork(models.Model): idartwork = models.AutoField( db_column="idArtwork", primary_key=True ) # Field name made lowercase. title = models.CharField(max_length=50, blank=True, null=True) date_created_month = models.IntegerField(blank=True, null=True) date_created_year = models.TextField( blank=True, null=True ) # This field type is a guess. comments = models.CharField(max_length=255, blank=True, null=True) width = models.DecimalField(max_digits=10, decimal_places=3, blank=True, null=True) height = models.DecimalField(max_digits=10, decimal_places=3, blank=True, null=True) artist = models.ForeignKey(Artist, models.DO_NOTHING, blank=True, null=True) class Meta: managed = False db_table = "artwork" class Artist(models.Model): idartist = models.AutoField( db_column="idArtist", primary_key=True ) # Field name made lowercase. artist_name = models.CharField( max_length=40, db_collation="utf8_general_ci", blank=True, null=True ) class Meta: managed = False db_table = "artist" My problem: In order to test the post request described in my description, … -
Django Rest Framework Djoser - saving JWT tokens in httpOnly cookies
Hey I'm looking for the correct way to implement saving JWT tokens in httpOnly cookies using JWT I'm not sure if thing I did is right. Changed Default authentication class in setting.py and added cookies settings REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ( "authorization.authentication.JWTCookiesAuthentication", ), } SIMPLE_JWT = { ... "AUTH_COOKIE": "access_token", # Cookie name. Enables cookies if value is set. "AUTH_COOKIE_DOMAIN": None, # A string like "example.com", or None for standard domain cookie. "AUTH_COOKIE_SECURE": False, # Whether the auth cookies should be secure (https:// only). "AUTH_COOKIE_HTTP_ONLY": True, # Http only cookie flag.It's not fetch by javascript. "AUTH_COOKIE_PATH": "/", # The path of the auth cookie. "AUTH_COOKIE_SAMESITE": "Lax", } Created custom authentication backend in authentication.py class JWTCookiesAuthentication(JWTAuthentication): def authenticate(self, request): header = self.get_header(request) if header is None: raw_token = request.COOKIES.get(settings.SIMPLE_JWT['AUTH_COOKIE']) or None else: raw_token = self.get_raw_token(header) if raw_token is None: return None validated_token = self.get_validated_token(raw_token) return self.get_user(validated_token), validated_token and added cookies in response in my view class EmailTokenObtainPairView(TokenViewBase): serializer_class = CustomTokenObtainPairSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) try: serializer.is_valid(raise_exception=True) except AuthenticationFailed: raise InActiveUser() except TokenError: raise InvalidToken() response = Response(serializer.validated_data, status=status.HTTP_200_OK) response.set_cookie( key=settings.SIMPLE_JWT["AUTH_COOKIE"], value=serializer.validated_data["access"], expires=settings.SIMPLE_JWT["ACCESS_TOKEN_LIFETIME"], secure=settings.SIMPLE_JWT["AUTH_COOKIE_SECURE"], httponly=settings.SIMPLE_JWT["AUTH_COOKIE_HTTP_ONLY"], samesite=settings.SIMPLE_JWT["AUTH_COOKIE_SAMESITE"], ) return response But what about refresh token and will that handle … -
Django channels - propagate exceptions to the client
I was wondering what is the best practice to propagate exceptions to the client using django-channels. My client is a Swift iOS app using URLSessionWebSocketTask. I got 3 main scenarios for example where exception is thrown and I want to notify the client. Authentication, using custom middleware. from api.jwt_handler import jwt_websocket_decode, get_device_id, get_auth_token from inbox.exceptions import WebSocketErrors class WebsocketAuthMiddleware: def __init__(self, app): self.app = app async def __call__(self, scope, receive, send): headers = scope["headers"] token = get_auth_token(headers) device_id = get_device_id(headers) if token is None or device_id is None: raise WebSocketErrors.invalid_bearer_token <--- Notify client user = await jwt_websocket_decode(token, device_id) if user is None: raise WebSocketErrors.invalid_bearer_token <--- Notify client scope['user'] = user return await self.app(scope, receive, send) I've tried wrapping __call__ in try statement, but I'm not sure how to propagate the error to the http transport layer, The client gets 1011 - There was a bad response from the server Connection rejection - handshake. class ConversationConsumer(AsyncWebsocketConsumer): async def connect(self): self.ws_conversation_id = self.scope["url_route"]["kwargs"]["conversation_id"] self.room_group_name = self.ws_conversation_id self.user = self.scope["user"] if user.can_participate_in_conversation(self.ws_conversation_id) is False: raise WebSocketErrors.not_authorized <--- Notify client await self.channel_layer.group_add(self.room_group_name, self.channel_name) await self.accept() Here I want to reject connection if user is not part of a given conversation id, to prevent abuse. … -
MultiValueDictKeyError when sending POST requests
I'm making an expense tracker web app, but when I want to send POST requests, it fails. models.py from django.db import models from django.contrib.auth.models import User class Token(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) token = models.CharField(max_length=48) def __str__(self): return "{}_token".format(self.user) class Expense(models.Model): text = models.CharField(max_length=225) date = models.DateTimeField() amount = models.BigIntegerField() user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return "{} -{}".format(self.date, self.amount) class Income(models.Model): text = models.CharField(max_length=255) date = models.DateTimeField() amount = models.BigIntegerField() user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return "{} +{}".format(self.date, self.amount) views.py from django.shortcuts import render from django.http import JsonResponse from json import JSONEncoder from django.views.decorators.csrf import csrf_exempt from web.models import User, Token, Expense, Income from datetime import datetime @csrf_exempt def submit_expense(request): this_token = request.POST['token'] this_user = User.objects.filter(token__token = this_token).get() now = datetime.now() Expense.objects.create( user = this_user, amount=request.POST['amount'], text=request.POST['text'], date=now ) return JsonResponse({ 'status': 'ok', }, encoder=JSONEncoder) I assume this way of sending POST requests are expired, but can't find a way to do it. -
How to render data from model to view?
I have this model called Coach and I want it to be accessible in the lesson_detail.html, because when I use the template {{ coach.first_name }}, nothing is showing up. I'm trying to pull the data from the model using get_object_or_404 but I'm not sure what I need to put in the argument for that. I tried a few things like id=pk or in the code below, first_name=first_name, but I got an error that the variable is not defined. views.py from django.shortcuts import render, get_object_or_404, reverse from django.views import generic, View from django.http import HttpResponseRedirect from .models import Lesson, Coach, Feedback from .forms import FeedbackForm class LessonDetail(View): def get(self, request, slug, *args, **kwargs): queryset = Lesson.objects.filter(status=1) lesson = get_object_or_404(queryset, slug=slug) coach = get_object_or_404(Coach, first_name=first_name) feedbacks = lesson.feedbacks.filter(approved=True).order_by('-created_on') liked = False if lesson.likes.filter(id=self.request.user.id).exists(): liked = True return render( request, "lesson_detail.html", { "lesson": lesson, "feedbacks": feedbacks, "coach": coach, "submitted_feedback": False, "liked": liked, "feedback_form": FeedbackForm(), }, ) models.py class Coach(models.Model): RECREATIONAL = 'recreational' FREESTYLE = 'freestyle' DANCE = 'dance' PAIRS = 'pairs' SPECIALIZATION_CHOICES = [ (RECREATIONAL, 'Recreational'), (FREESTYLE, 'Freestyle'), (DANCE, 'Dance'), (PAIRS, 'Pairs'), ] first_name = models.CharField(max_length=80) last_name = models.CharField(max_length=80) email = models.EmailField(max_length=100) bio = models.CharField(max_length=140, help_text="Enter a brief bio") image = CloudinaryField('image', default='placeholder') … -
I am building a product review app in my Django eCommerce project. I can't get my review form to display on a template from the main shop app
Here is my set up: using Django 3.2.21. bootstrap4 reviews/views.py from django.shortcuts import render, redirect, get_object_or_404 from django.contrib import messages from shop.models import Product from .models import Reviews from .forms import ReviewForm def review(request, product_id): product = get_object_or_404(Product, pk=product_id) if request.method == 'POST': review_form = ReviewForm(request.POST) if review_form.is_valid(): review_form.save() messages.success(request, 'Successfully reviewed product') return redirect(reverse('product_detail', args=[product.id])) else: messages.error(request, 'Failed to add product. \ Please check the form data is correct') else: form = ProductForm() template = 'shop/product_detail.html' context = { 'review_form': review_form, } return render(request, template, context) shop/product_detail.html <h3>Leave a Review</h3> <form method="post" action="{% url 'review' product.id %}"> {% csrf_token %} {{ review_form|crispy }} <input type="submit" value="Submit review"> </form> reviews/urls.py from django.urls import path from . import views urlpatterns = [ path('review/<int:product_id>/', views.review, name='review'), ] The model and form file to me look ok they are also set up in the revies app. The main project level urls.py path looks ok. I have other apps in the project all set up ok. On the product_detail template there is another form for adding item to cart which is working. I have tried changing around urls and rewriting the view differently but nothing working. The title and submit button are displaying with … -
django.db.utils.ProgrammingError: relation "iptoc" does not exist
I have seen all of the similarly titled questions. Case is different: The problem arises when running the unittest. I had to import some foreign tables because they already had data in them (country region city ) data. So I had to create the Model as managed = false class Iptoc(models.Model): id_ip = models.IntegerField(primary_key=True) ip_from = models.IntegerField() ip_to = models.IntegerField() country_code2 = models.CharField(max_length=2) threecode = models.CharField(max_length=3) country_name = models.CharField(max_length=40) class Meta: managed = False db_table = 'iptoc' When I do a query in a view it works 100% correct that is, it does use the table. def index_country(request): # getting the hostname by socket.gethostname() method hostname = socket.gethostname() ## getting the IP address using socket.gethostbyname() method ip_address = socket.gethostbyname(hostname) ## printing the hostname and ip_address print(f"Hostname: {hostname}") print(f"IP Address: {ip_address}") x = 18874378 record = Iptoc.objects.get(ip_to__gte=x,ip_from__lte=x) pais = record.country_name print(pais) The table in my postgresql is called iptoc (no capital letters) When I run this test: class HomeTests(TestCase): def test_home_view_status_code(self): url = reverse('country') response = self.client.get(url) self.assertEquals(response.status_code, 200) I get: File "/home/alvar/PycharmProjects/Carpeta9Abril/venv9Abril/lib/python3.9/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: relation "iptoc" does not exist LINE 1: ... "iptoc"."threecode", "iptoc"."country_name" FROM "iptoc" WH... -
How to resolve missing 1 required positional argument: 'get_response' in Django
I am new to Django and I want to add a Middleware for JWT Authentication. I am using Django version 4.2.6 My Middleware code is as follows: import jwt from django.http import JsonResponse from django.conf import settings from django.utils.deprecation import MiddlewareMixin class TokenMiddleware(MiddlewareMixin): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): # Check if the request has an "Authorization" header authorization = request.META.get('HTTP_AUTHORIZATION') if authorization and authorization.startswith('Bearer '): token = authorization.split(' ')[1] jwks_client = jwt.PyJWKClient(settings.JWT_VERIFY_URL) header = jwt.get_unverified_header(token) key = jwks_client.get_signing_key(header["kid"]).key try: jwt.decode(token, key, [header["alg"]]) except jwt.ExpiredSignatureError: return JsonResponse({'error': 'Token has expired'}, status=401) except jwt.DecodeError: return JsonResponse({'error': 'Token is invalid'}, status=401) else: return JsonResponse({'message': 'Authentication Bearer Token is required.'}) response = self.get_response(request) return response I have registered my Middleware in settings.py. I have been trying to fix this error but nothing really helped. It triggers when get_response is called. For this code I am getting the following error: Traceback (most recent call last): File "/home/abdulai/projects/abdulai/holden/nyc-transactions/nyc-transactions-backend/venv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/abdulai/projects/abdulai/holden/nyc-transactions/nyc-transactions-backend/venv/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/abdulai/projects/abdulai/holden/nyc-transactions/nyc-transactions-backend/venv/lib/python3.10/site-packages/django/views/decorators/csrf.py", line 56, in wrapper_view return view_func(*args, **kwargs) File "/home/abdulai/projects/abdulai/holden/nyc-transactions/nyc-transactions-backend/venv/lib/python3.10/site-packages/django/views/generic/base.py", line 104, in view return self.dispatch(request, *args, **kwargs) File "/home/abdulai/projects/abdulai/holden/nyc-transactions/nyc-transactions-backend/venv/lib/python3.10/site-packages/rest_framework/views.py", line 492, in dispatch request … -
Problems with Summernote and crispy-forms in Django
I have 2 problems: (1) I got Summernote working in the admin create-a-post section, but I can't figure out how to incorporate it into the publicly-facing HTML form (at https://example.com/post/new/), and (2) I'm using crispy_forms, and when I make a post in Summernote in admin with a picture and/or some HTML formatting tags, the post renders as plain-text, including the HTML tags, which is ugly. I've tried removing the crispy tag and replacing it with the "safe" keyword, but the HTML still renders in plain-text. How do I get Summernote to render properly with crispy_forms? Here's my code: post_form.html {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Blog Post</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Post</button> </div> </form> </div> {% endblock content %} the main urls.py from django.contrib import admin from django.contrib.auth import views as auth_views from django.urls import path, include from users import views as user_views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('register/', user_views.register, name='register'), path('profile/', user_views.profile, name='profile'), path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'), 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( … -
Paypal Payment gateway integration code=NO_BUSINESS
I am trying to integrate paypal payment gateway to my html page and its always returning "Things don't appear to be working at the moment. Please try again later." in paypal sandbox page paypal_dict = { 'buisness':"sb-xxxxxxxxxxx.business.example.com", 'amount': cart_total_amount , 'currency': 'INR', 'receipt': 'order-item-number-' + str(order.id), 'invoice_number': 'INVOICE_NO-' + str(order.id), 'notify_url': 'http://{}{}'.format(host, reverse("uwapp:paypal-ipn")), 'return_url': 'http://{}{}'.format(host, reverse("uwapp:payment_completed")), 'cancel_url': 'http://{}{}'.format(host, reverse("uwapp:payment_failed")), } # Generate the Razorpay payment button payment_button = PayPalPaymentsForm(initial=paypal_dict) return render(request, 'uwapp/checkout.html', { 'payment_button': payment_button }) -
Django model not Associating with another model object
I am using Django to create an application where I have an Employee model that needs to be associated with a Company model. I am able to associate the User model with the Employee model correctly, but I am having trouble associating the Company object with the Employee object. My view: from django.shortcuts import render from django.http import HttpResponse from company.models import Company from .models import Employee from .forms import UserForm, CompanyForm from django.contrib.auth.models import User import random, string from django.db import IntegrityError def new(request): # Initialize forms user_form = UserForm(request.POST or None) company_form = CompanyForm(request.POST or None) # Check if the request is a POST request if request.method == 'POST': # Check if both forms are valid if user_form.is_valid() and company_form.is_valid(): email = user_form.cleaned_data['email'] # Check if a user with this email already exists try: user = User.objects.get(email=email) user_created = False except User.DoesNotExist: user = User(username=email, email=email) random_password = User.objects.make_random_password() user.set_password(random_password) user.save() user_created = True # Save the company form data company = company_form.save() # Check if an Employee already exists for this user try: employee = Employee.objects.get(user=user) employee_created = False except Employee.DoesNotExist: employee = Employee(user=user, company=company) employee.save() employee_created = True # Return appropriate response based on what was … -
Circular import during run multiprocessing
I have example like this: File models.py from django.db import models class Document(models.Model): name = models.CharField(max_length=20) text = models.CharField(max_length=200) File db_request.py from .models import Document def get_all_documents(): return Document.objects.all() File services.py from multiprocessing import Process from .db_request import get_all_documents def stream(): docs = get_all_documents() def start_streams_documents(): pr = Process(target=stream) pr.start() pr.join() File admin.py from .models import Document from .services import start_streams_documents @admin.register(Document) class MachineAdmin(admin.ModelAdmin): list_display = ('name','text') change_list_template = 'admin/document_table_changelist.html' def get_urls(self): urls = super().get_urls() my_urls = [path('start_streams/', self.start_streams)] return my_urls + urls def start_streams(self, request): start_streams_documents() return HttpResponseRedirect("../") If i call in services.py stream, i get an error Apps aren't loaded yet.. Ok, let's add import django django.setup() to db_request.py at first. Then i'll get an error circular import. The example is as simple as possible, what am I doing wrong? If i call stream without multiprocessing, it will work Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Users\fr3st\AppData\Local\Programs\Python\Python311\Lib\multiprocessing\spawn.py", line 120, in spawn_main exitcode = _main(fd, parent_sentinel) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\fr3st\AppData\Local\Programs\Python\Python311\Lib\multiprocessing\spawn.py", line 130, in _main self = reduction.pickle.load(from_parent) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\fr3st\Desktop\Screener V3\app\documents\services.py", line 3, in <module> from .db_request import get_all_documents File "C:\Users\fr3st\Desktop\Screener V3\app\documents\db_request.py", line 2, in <module> django.setup() File "C:\Users\fr3st\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File … -
How to write a classed based view in Django when we have an Order model that has multiple OrderRow records?
I have an Order model such as below: class Order(models.Model): customer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) status = models.CharField(max_length=1, choices=ORDER_STATUS, default="D") def __str__(self) -> str: return self.customer.name + " Order No. " + str(self.pk) and OrderRow: class OrderRow(models.Model): product = models.ForeignKey("products.Product", on_delete=models.CASCADE) quantity = models.IntegerField() unit = models.ForeignKey("products.Unit", on_delete=models.CASCADE) order = models.ForeignKey(Order, on_delete=models.CASCADE) def __str__(self) -> str: return self.product + " " + self.quantity + " " + self.unit I need to write a classed based view than when user enters in this page a new order automatically created for current user and the user be able to add OrderRows to the current Order. -
celery redis key unacked issue
I am using the Glitchtip service, which employs Celery to initiate worker processes for job processing. This setup involves a combination of Celery and Redis, where Redis serves as a message broker. Upon sending a substantial number of requests, I've noticed a spike in the Redis key named "unacked," which eventually causes Redis to run out of memory. In my environment configuration, I have set the following parameters: CELERY_ACKS_ON_FAILURE_OR_TIMEOUT is set to False. CELERY_ACKS_LATE is set to True. I'm wondering if there are any additional environment parameters that I should consider setting in order to better control the processing rate. Your assistance in this matter is greatly appreciated. Ref -> https://gitlab.com/glitchtip -
img not showing in html, while online urls are working
I'm trying to build my portfolio using django but i have trouble with it. I cannot add my photo in that. Even if i mentioned the correct path it's not displaying while online image are displaying properly.This where my profile photo is located <!-- Title Bar --> <section class="section-gap"> <div class="row featurette"> <div class="col-md-7"> <h2 class="fs-1 featurette-heading">PARAMASIVAN T</h2> <div class="fs-2 text-muted">Web Developer</div> <p class="lead">“Digital design is like painting, except the paint never dries.”</p> </div> <div class="col-md-5"> <img src="D:\Django_Projects\porfolio\mysite\myapp\templates\myapp\profile.png" alt="profile"> </div> </section> what is the solution for this problem? -
Django Polymorphic behaviour (Custom ForeignKey) without using GenericForeignKey
I'm working with a legacy DB that has fields like edited_by_type, and edited_by_id in many tables. This is basically a polymorphic relation for RubyOnRails persons. This represents a FK relation to multiple models using combinations of these two fields. for example, the value of edited_by_type can be either user, admin, or client. These are 3 different tables. so now you can guess that it's basically a unique constraint of edited_by_type, and edited_by_id together, where edited_by_type is used to determine the type of person (table) and then query that table using edited_by_id. I have a fairly good understanding of Django's GenericFK field that uses the contentType table internally. but since this is a legacy DB and I don't want to use the ContentType table at all it requires creating migrations and entries in the contenttype table. What I'm looking for is a customFk or (even customGenericFK) solution that somehow manages this and allows us to query the db as easily as we can. e.g something like the below (open to any other approach that doesn't involve creating a CustomFK). here is what I've tried so far. class CustomFK(models.ForeignKey): def __init__(self, fk_models, on_delete, **kwargs): for model in fk_models: super().__init__(to=model, on_delete=on_delete, **kwargs) # … -
I am trying to convert a WEBP image to JPEG and create a ZIP file but when I type in the ZIP it is still WEBP
image.read() is the image stored with django which is in WEBP format. ` image_read = BytesIO(image.read()) image_read.seek(0) image_converted = BytesIO() original_image = Image.open(image_read).convert('RGB') original_image.save(image_converted, format='JPEG') image_converted.seek(0) image_data = image_converted.getvalue() zip_file.writestr(f'{filename}', image_data) ` A zip file images in JPEG format -
Django form field feed with javascript produced list
I'm learning Django through a recipe posting website, in the recipe form I want to pass an ingredient list that is created with a java script function on the fly. I have two buttons, one to create the list, and the final submit button when the recipe form is ready. The problem is that every time the ingredients "adding ingredient button" is clicked, the form is submitted, since it is not valid it resets the whole form. How can I integrate the java script without submitting the form? I've tried many solutions that I've seen everywhere to no avail, so any help is welcome. Model. class Recipe(models.Model): """Represents the whole recipe description""" recipe_name = models.CharField(max_length=100, default=None) user_name = models.ForeignKey(User, on_delete=models.DO_NOTHING) description = models.TextField(max_length=500, help_text='Enter a brief description of the recipe') ingredients = models.TextField(max_length=1000, help_text='enter all the ingredients with quantities') cooking_time = models.CharField(max_length=50) preparation = models.TextField(max_length=3000, help_text='Enter the steps to prepare the recipe') date = models.DateField(auto_now_add=True) script. class Recipe(models.Model): """Represents the whole recipe description""" recipe_name = models.CharField(max_length=100, default=None) user_name = models.ForeignKey(User, on_delete=models.DO_NOTHING) description = models.TextField(max_length=500, help_text='Enter a brief description of the recipe') ingredients = models.TextField(max_length=1000, help_text='enter all the ingredients with quantities') cooking_time = models.CharField(max_length=50) preparation = models.TextField(max_length=3000, help_text='Enter the steps to … -
Django blog UserProfile model
I am creating a Django blog app and I already set up a Post and Comment model both linked with the built in Django User model via these fields below: POST MODEL writer = models.ForeignKey( User, on_delete=models.CASCADE, related_name="blogs" ) COMMENT MODEL writer = models.ForeignKey( User, on_delete=models.CASCADE, related_name='user_comments') If I add a UserProfile model to this blog app, would I need to change the foreign key relationship in my post model to this: writer = models.ForeignKey( UserProfile, on_delete=models.CASCADE, related_name="blogs" ) Thanks P.S. I want only admin users to have profiles and to be able to click on their profiles to view the posts they have created. Regular users do not have the ability to create posts. They can only comment and like the posts. -
Urls in CSS files not getting signed through django-storages
For example, my css code has this image file: background: url('/static/studyspot5/images/shapes/footer_sass.png'); And it does not render on my AWS site I have the following relevant code in my settings.py: if USE_S3: STATICFILES_LOCATION = 'static' MEDIAFILES_LOCATION = 'media' MEDIA_URL = f'https://{CLOUDFRONT_DOMAIN}/{MEDIAFILES_LOCATION}/' MEDIA_ROOT = f'https://{AWS_S3_CUSTOM_DOMAIN}/static/{MEDIAFILES_LOCATION}/' STATIC_URL = 'https://%s/%s/' % (CLOUDFRONT_DOMAIN,STATICFILES_LOCATION) STATIC_ROOT = 'https://%s/%s/static/' % (AWS_S3_CUSTOM_DOMAIN,STATICFILES_LOCATION) STORAGES = { "default": {"BACKEND": 'custom_storages.MediaStorage'}, "staticfiles": {"BACKEND": 'custom_storages.StaticStorage'}, "OPTIONS": { "bucket_name": AWS_STORAGE_BUCKET_NAME, "region_name": AWS_S3_REGION_NAME, # "verify": AWS_S3_VERIFY, "signature_version": AWS_S3_SIGNATURE_VERSION, "cloudfront_key_id": AWS_CLOUDFRONT_KEY_ID, "cloudfront_key": AWS_CLOUDFRONT_KEY, "custom_domain": CLOUDFRONT_DOMAIN, }, } The CSS file (and all other static content) is served as a signed URL just fine, e.g. using the following code: <link rel="stylesheet" href="{% static 'studyspot5/css/style.css' %}"> But for those urls inside of CSS files, it will only pass the url of the file, without signing it (no parameters). Here is the resulting request headers. Note the referer URL is signed, but the darn background image from the CSS is not! -
how can i send file from s3 into the user in django?
i have a website , this website you can use it to upload a file. after that the users will be able to download what you have uploaded in that website. i upload a file , and this file is getting saved inside a bucket in AWS-S3. now how can i read that file from the bucket and send it to the user ? this is my function for donwloading : class Download(View): def get(self, request): try: if request.session["language"] == "en": the_path_of_templates = "website/en/" else: the_path_of_templates = "website/ar/" except: the_path_of_templates = "website/en/" ######################################################### # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ######################################################### try: the_file = KarafetaProduct.objects.all()[0] with open(os.path.join(BASE_DIR, str(the_file.file)), "rb") as file: file_data = file.read() response = HttpResponse(file_data, content_type='application/vnd.microsoft.portable-executable') response['Content-Disposition'] = 'attachment; filename="{}"'.format(str(the_file.name)) return response except: return render(request=request, template_name=f"{the_path_of_templates}home.html") this is the link of the file in s3 : karafeta-bucket.s3.amazonaws.com\Python-3.11.5_3_q9ZN0gC.exe -
Django Email Configuration Issue: ConnectionRefusedError [WinError 10061]
Question: I'm encountering a ConnectionRefusedError in my Django project when trying to send emails. The error message is as follows: ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it Details: Context: I'm using Django for a web application. I have configured email settings in the settings.py file to use a custom email domain hosted on a Linode server. Email Configuration (settings.py): EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'your_email_host' # e.g., 'smtp.yourdomain.com' EMAIL_PORT = 587 # Use the appropriate port for your email provider EMAIL_USE_TLS = True # Set to True if your email provider requires TLS EMAIL_HOST_USER = 'your_email@example.com' # Your full email address EMAIL_HOST_PASSWORD = 'your_email_password' # Your email password DEFAULT_FROM_EMAIL = 'webmaster@example.com' # Your default sender address SERVER_EMAIL = 'webmaster@example.com' # The address that error messages come from I checked the email server status; it's up and running. Question: What could be causing this ConnectionRefusedError? Are there any additional steps I should take to troubleshoot this issue? I am currently testing the email on my local host before making the changes to the production server Any insights or guidance on resolving this issue would be greatly appreciated. Thank you! -
Django request method defaults to GET while the tutorial I'm working with is using a POST in the code
I am following a django video tutorial to build a blog app. I am currently working in the view.py folder and creating the comment section. I followed every step carefully but i got an error while running the code. i will drop the code i wrote i wrote below and the error i'm recieving from django.shortcuts import render, redirect from .models import Post from .forms import CommentForm def frontend(request): posts = Post.objects.all() return render(request, 'blog/frontend.html', {'posts': posts}) def post_detail(request, slug): post = Post.objects.get(slug=slug) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect('post_detail', slug=post.slug) else: form = CommentForm return render(request, 'blog/post_detail.html', {'post': post, 'form': form}) screenshot of the webpage I tried changing the if statement to a get, but i am not getting the django form as expected