Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Wagtail one-to-one object hierarchy with enum type field
I have a wagtail site and I want to create an object hierarchy in a one-to-one matter, but with multiple options. Basically, I want that the database setup look slike this: CREATE TABLE products ( id PRIMARY KEY, product_type VARCHAR(10) CHECK (product_type IN ('BOOK', 'SHIRT', ...)), product_name VARCHAR(255), product_description TEXT, ... ); CREATE TABLE product_shirts ( id PRIMARY KEY, product_id integer REFERENCES products (id), size varchar(255), ... ); CREATE TABLE product_books ( id PRIMARY KEY, product_id integer REFERENCES products (id), author varchar(255), ... ); It is pretty straigt forward to create a regular one-to-one relationship with setting ParentalKey in the derived model. However, I want to also have an enum-type field in the parent model to check which product type we have, so that I can do something like that in my ProductsView: if object.product_type == 'SHIRT': # display additional shirt attributes elif object.product_type == 'BOOK': # display book attributes else: # unknown type, should not happen I know, that with a one-to-one relationship in wagtail I could just simply call product.shirtwhich would raise an exception, if the product is not a shirt. But it seems very cumbersome to have nested try-catch blocks if I have many different product types... … -
Azure AD Authentication with Django on AWS ALB: Redirect URI problem
I am trying to integrate Microsoft authentication with my Django app using the django_auth_adfs package. However, I encountered an error regarding a mismatch in the redirect URI. I have followed the documentation provided by django_auth_adfs for configuring Azure Active Directory integration. In my Azure portal, I registered the application and added https://myhost/oauth2/callback to the Web Redirect URLs as instructed. When attempting to authenticate, I receive the following error message with http URI instead of https: > AADSTS50011: The redirect URI 'http://myhost/oauth2/callback' specified in the request does not match the redirect URIs configured for the application '944fce1cxxxx-xxx-xxxx-4f2abba56fb6'. Make sure the redirect URI sent in the request matches one added to your application in the Azure portal. Navigate to https://aka.ms/redirectUriMismatchError to learn more about how to fix this. I have created a record for the host in route53 and configured my ALB with ACM certificate. I am using below settings file: from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY') DEBUG = False SITE_ID = 1 ALLOWED_HOSTS = ['myhost'] CSRF_TRUSTED_ORIGINS = ['myhost'] # Application definition INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", 'django.contrib.sites', 'workspaces', 'django_auth_adfs', 'django_extensions', ] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", … -
Stock Quantity Not Updating on Size Selection in Django Template with JavaScript
Problem Description: I'm working on a Django project where a product can have multiple size variants, and each size has its own stock quantity. I want to display the stock information dynamically when a user selects a size using JavaScript. However, the stock information is not updating as expected. It always shows undefined in stock or Only undefined left, even though I can see the correct stock data in the browser console. Models: class Size(models.Model): name = models.CharField(max_length=50) class Product(models.Model): title = models.CharField(max_length=255) class ProductStock(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="stocks") size = models.ForeignKey(Size, on_delete=models.CASCADE, blank=True, null=True) uploded_stock_quantity = models.PositiveIntegerField(default=0) stock_quantity = models.PositiveIntegerField(default=0) reserved_stock = models.PositiveIntegerField(default=0) def available_stock(self): return self.stock_quantity - self.reserved_stock Views: from django.shortcuts import render, get_object_or_404 def product_detail_view(request, pid): product = get_object_or_404(Product, pid=pid) sizes = product.size.filter(product=product) product_stocks = ProductStock.objects.filter(product=product) size_stock_data = { str(stock.size.id): { 'stock_quantity': stock.stock_quantity, 'uploaded_stock_quantity': stock.uploded_stock_quantity } for stock in product_stocks } return render(request, 'core/product_detail.html', { 'product': product, 'sizes': sizes, 'size_stock_data': size_stock_data }) Template: {{ size_stock_data|safe|json_script:"size-stock-data" }} <div class="u-s-m-b-15"> <div class="pd-detail__inline"> <span class="pd-detail__stock" id="uploaded-stock">-</span> <span class="pd-detail__left" id="remaining-stock">-</span> </div> </div> {% if sizes %} <div class="u-s-m-b-15"> <span class="pd-detail__label u-s-m-b-8">Size:</span> <div class="pd-detail__size"> {% for s in sizes %} <div class="size__radio"> <input type="radio" id="size_{{ s.id }}" name="size" value="{{ s.id }}" … -
How to style a Django crispy-form label
I'm developing a small project using Django v5 and Bootstrap v5. At this stage I'm just playing around with the registration and login pages but I'd like to style the form using crispy-form and the crispy FormHelper. I can change the displayed label but (so far) I've been unable to make the label bold and/or underlined to show that it is a required field (rather than using crispy's asterisk). For what it is worth here is my forms.py file: from django import forms from django.contrib.auth import get_user_model from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit, Field, Layout class LoginForm(forms.Form): username = forms.CharField(widget=forms.TextInput(attrs={'autofocus': 'autofocus'})) password = forms.CharField(widget = forms.PasswordInput) class UserRegistrationForm(forms.ModelForm): password = forms.CharField( label = 'Password', widget = forms.PasswordInput ) password2 = forms.CharField( label = 'Repeat password', widget = forms.PasswordInput ) class Meta: model = get_user_model() fields = ['username','email','first_name','last_name'] widgets = { "username": forms.TextInput(attrs={'autofocus': 'autofocus'}), } def clean_password2(self): cd = self.cleaned_data if cd['password'] != cd['password2']: raise forms.ValidationError("Passwords don't match!") return cd['password2'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.fields['username'].label= "User Name" self.fields['username'].help_text= "This will be your Login ID and must be unique" #self.helper.layout = Layout( #Field('username', label='User Name - Doug', css_class="fs-2") #) self.helper.add_input(Submit('submit', 'Register')) Note - the commented … -
"Unable to authenticate Django user with email instead of username
I'm trying to implement email-based authentication in Django instead of using the default username. I’ve updated my User model and authentication backend, but I’m still unable to authenticate users with their email addresses. views.py from django.shortcuts import render,HttpResponseRedirect from .forms import UserLoginForm,UserSignUpForm from django.contrib.auth import authenticate,login,logout,get_user from django.contrib import messages from .models import UserRegister # Create your views here. def home(request): return render(request,'home.html') def form(request): if request.method=="POST": if 'login' in request.POST: login_form = UserLoginForm(request,data=request.POST) signup_form =UserSignUpForm() if login_form.is_valid(): email = login_form.cleaned_data.get('email') password = login_form.cleaned_data.get('password') user = authenticate(request,email=email,password=password) if user is not None: login(request,user) messages.success(request, "Successfully logged in!") return HttpResponseRedirect('/home') else: print("Authentication Failed") messages.error(request,"Invalid email or password") login_form.add_error(None,"Invalid email or password") else: messages.error(request,"Please fix the errors below.") print("Login form error:",login_form.errors) print("Non-field errors:", login_form.non_field_errors()) for field in login_form: print(f"Field Error: {field.name} - {field.errors}") print(request.POST) if 'signup' in request.POST: login_form = UserLoginForm() signup_form =UserSignUpForm(request.POST) if signup_form.is_valid(): form_info = UserRegister( username=signup_form.cleaned_data.get('username'), email=signup_form.cleaned_data.get('email'), password=signup_form.cleaned_data.get('password1') ) form_info.save() messages.success(request, "Successfully signup!") return HttpResponseRedirect('/home') else: messages.error(request,"Please fix the errors below.") print("Login form error:",signup_form.errors) print("Non-field errors:", signup_form.non_field_errors()) for field in signup_form: print(f"Field Error: {field.name} - {field.errors}") else: login_form = UserLoginForm() signup_form=UserSignUpForm() return render(request,'form.html',{'login_form':login_form,'signup_form':signup_form}) form.py from django import forms from django.contrib.auth.forms import UserCreationForm,AuthenticationForm from .models import UserRegister from django.contrib.auth import … -
Django: ORM player substitution, checking __isnull=False versus is not None
I have a Django model Player. Now this model has a save method which goes like this: def save(self, *args, **kwargs): """ Overrides the save method to convert the 'name' attribute to uppercase before saving. """ player = Player.objects.filter( Q(fide_id=self.fide_id, fide_id__isnull=False) | Q(lichess_username=self.lichess_username, lichess_username__isnull=False) | Q( name=self.name, email=self.email, email__isnull=False, name__isnull=False, ) ) if player.exists(): p = player.first() for k, v in self.__dict__.items(): if k == "_state": continue if v is None: self.__dict__[k] = p.__dict__[k] if self.check_lichess_user_exists(): self.get_lichess_user_ratings() print(f"id: {self.id}") super().save(*args, **kwargs) This is intended to look for a player which has either: The same fide_id (which should not be null, as then I would be considering two players with null values in their fide id to be the same) The same lichess_username (idem) The same combination of username and email (idem) Then, if such a player exists, then set every field of the player we're adding (if it is None) to the fields of the player already in the database. Then super().save() should overwrite the player with the same id, according to the Django docs: You may have noticed Django database objects use the same save() method for creating and changing objects. Django abstracts the need to use INSERT or … -
How does one correctly define an index for efficiently querying the reverse relation for ForeignKey fields? (Django)
So I've spent days searching on and off for an answer to this question, and much to my surprise, I can't seem to find anbyone asking this specific question, nor any mentions of the confusion I have around it. My confusion lies, I suppose, in not being sure just how it is that Django builds queries under the hood, around querying a model_set reverse relation, or its related_name is specified as. It would be ideal if beginning an ORM query with parent_instance.related_name worked exactly like RelatedModel.objects does, so that, for example, the query parent_instance.related_name.filter(token__in=somelist) was able to utilize a simple field index on the "token" field created with db_index=True, just like how such an index would be able to be utilized with RelatedModel.objects.filter(token__in=somelist). However, these two queries are not equivalent; to be equivalent, the second query would have to be changed to RelatedModel.objects.filter(parent=parent_instance, token__in=somelist) (or the reverse order, RelatedModel.objects.filter(token__in=somelist, parent=parent_instance)). This leads me to believe that, in order to take advantage of indexing when querying Reverse foreignKey relations, the parent model likely n[eeds to be part of whatever indexes you plan to utilize. If one understands databases under the hood (which I do to an extent, though it is not … -
Configuring wagtail-markdown to use Prism instead of Pygments
Is there a way to inject a class into the <code> tag produced by wagtail-markdown so that I can style my Markdown code blocks with Prism instead of Pygments, which is the default syntax highlighter? Ideally, I'd like to choose the language in the first line of my Markdown as in e.g. :::python for i in range(5): print(i**2) and have it add the class="language-python" attribute required by Prism to style the block nicely. -
Accessing a foreign key's base classes's fields in UniqueConstraint
In the UniqueConstraint for personality -> language, I'm getting the error FieldDoesNotExist For example, if my code looked like this: class LanguageModel(models.Model): language = models.CharField( max_length=16, default="en", ) class Meta: abstract = True class PersonModel(LanguageModel): created_at = models.DateTimeField(editable=False, auto_now_add=True) updated_at = models.DateTimeField(editable=False, auto_now=True) class Meta: managed = True db_table = "PersonModel" class CollectionofPeople(models.Model): id = models.UUIDField(primary_key="True", default=uuid.uuid4, editable=False) created_at = models.DateTimeField(editable=False, auto_now_add=True) updated_at = models.DateTimeField(editable=False, auto_now=True) is_default = models.BooleanField(default=False) personality = models.ForeignKey( "PersonModel", null=True, on_delete=models.CASCADE, ) class Meta: managed = True db_table = "CollectionofThings" constraints = [ models.UniqueConstraint( fields=["personality__language", "id"], name="unique_personality_language", ) ] Is it possible to access the personality language in a UniqueConstraint? Or more generally, can I access a foreign key's abstract base class's field? -
ValueError: The field exam.Question.created_by was declared with a lazy reference to 'add_user.user', but app 'add_user' isn't installed
This error keeps appearing, even though I have the add_user app installed in my directory and registered in the settings.py file. -
pycharm 2024.3.5 django docker compose set project path in container
I have a docker compose django project that run fine in a terminal on the server and I'm trying to setup Pycharm for development debugging. In my docker-compose .py I have a volume mapping the project root on the host file system to the container: volumes: - ../:/code So I would expect that when the project is run/debug it would build the root project directory in the container directory /code but instead it is in /opt/project directory. Docker is running on Ubuntu 24.04 on an ESXi 8 VM. How can I set the path of the project in the container to use /code and not /opt/project ? I've tried path mapping in the run/debug configurations /opt/my_app=/code setting the working directory /opt/my_app I've also spent hours looking online for any information regarding but most of what I can find is for older versions of Pycharm and is no longer valid. -
got multiple values for argument 'request' in get_user_colls method of Django Ninja Extra
I'm using Django Ninja Extra to write an API controller. Here is my code: @api_controller('', tags=['User'], auth=NOT_SET, permissions=[]) class User: @http_get('/user/colls', response=List[schemas.UserCollsOut], auth=JWTAuth()) @paginate(PageNumberPagination, page_size=10) def get_user_colls(self, request): data = userModels.UserCollection.objects.filter(user=request.auth) return data When I run this code, I get the following error: TypeError: User.get_user_colls() got multiple values for argument 'request' "GET - User[get_user_colls] /api/v1/user/colls" ("User.get_user_colls() got multiple values for argument 'request'",) User.get_user_colls() got multiple values for argument 'request' Traceback (most recent call last): File "C:\Users\Administrator\PycharmProjects\lmew\venv\lib\site-packages\ninja_extra\operation.py", line 214, in run result = self.view_func(request, **ctx.kwargs) File "C:\Users\Administrator\PycharmProjects\lmew\venv\lib\site-packages\ninja_extra\controllers\route\route_functions.py", line 97, in as_view result = self.route.view_func( TypeError: User.get_user_colls() got multiple values for argument 'request' Internal Server Error: /api/v1/user/colls I don't quite understand why this error occurs. The request parameter should only be passed once. I've tried looking through the Django Ninja Extra documentation but haven't found a relevant solution. -
my django app ORM is not working properly
I had my project set up on my local computer, and in the beginning, everything was working file. for past couple of days. my django ORM is not working properly it showing failed SQL error there is another issue is when ever i hit a request, the first request is working fine but if i hit the request after that without refreshing/reloading django server it is showing internal server error. if i stop/reload server then if i hit request its working. we are using mongoDb as database, pymongo version : 4.10.1 django version : 3.1.12 -
Ubuntu server with Django, Gunicorn, Nginx does not give static
The file /var/log/nginx/error.log contains errors of the following type: [error] 714#714: *5 open() "/home/<user>/<projects>/static/css/custom.css" failed (13: Permission denied), client: ip, server: domain, request: "GET /static/css/custom.css HTTP/1.1", host: "domain", referrer: "http://domain/" The following settings are specified in the /etc/nginx/sites-available/<project> file: server { listen 80; server_name <domain>; location = /favicon.ico { access_log off; log_not_found off; } location /collected_static/ { root /home/<user>/<project>; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } The following settings are specified in the /etc/systemd/system/gunicorn.service file: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=vsevolod Group=www-data WorkingDirectory=/home/<user>/<project> ExecStart=/home/<user>/<project>/myvenv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ config.wsgi:application [Install] WantedBy=multi-user.target В файле settings.py указаны следующие настройки: STATIC_URL = '/static/' STATICFILES_DIRS = ( BASE_DIR / 'static', ) STATIC_ROOT = os.path.join(BASE_DIR, 'collected_static') Am I right in understanding that in the Nginx configuration file after location I need to specify exactly the directory that is generated after the python3 manage.py collectstatic command, so that Nginx gives it exactly that one? I ran the command sudo -u www-data stat /home/<user>/<project>/collected_static and got an error about the user not having enough rights. I ran the command sudo gpasswd -a www-data <user>, rebooted Nginx and the server just in case, but the statics still didn't … -
Django same slug but using different URL path
I am making a documentation site to self-host for myself; learning Django at the same time. I am at the point where I am starting to populate the website. I am wondering if there is a possibility to have two posts that have the same slug, but they are part of a different category. For example, I have two posts that are named "virus". One is under the category of "computer science" and the other is under the category of "heathcare". The website would link those pages as: .../healthcare/virus/ .../computer-science/virus/ Is there a way to use the same slug depending on the value of another field (e.g. category field) or some other technique? TIA -
i can develop a bulk massge software
How can I develop software that allows me to send bulk messages to customers via WhatsApp by importing a CSV file, using the official WhatsApp API, ensuring that my account remains active and does not get blocked? I need guidance on how to set up and manage this effectively. How can I develop software that allows me to send bulk messages to customers via WhatsApp -
as django fresher developer what sequence of topics need to be done? [closed]
please elaborate it I tried learning it with some tutorials of youtube, but not clear like its enough or not. I currently worked on shells, migrations, authentication and everything I need to do. I wanna land a good job as fresher in this field as python developer -
How can I change device creation to be managed only through the Client model, and restrict direct device creation?
I currently have a system where devices can be created and managed through the Device model directly. However, I want to change it so that devices can only be added or deleted through the Client model, and not directly through the Device model. Specifically, I want to: Prevent creating or modifying devices directly via the Device model. Allow adding and deleting devices only through the Client model, so when working with a Client, I can manage their devices. Ensure that when adding a device to a Client, I don’t need to re-enter the Client information, as I’m already in the context of that Client.class Client(BaseModel): inn = models.CharField(max_length=14, unique=True, verbose_name="СТИР", validators=[validate_inn]) name = models.CharField(max_length=255, verbose_name="Имя пользователя") pinfl = models.CharField(max_length=14, blank=True, null=True, verbose_name="ПИНФЛ") phone = models.CharField(max_length=13, verbose_name="Телефон", null=True, blank=True) bank_name = models.CharField(max_length=255, verbose_name="Банк") address = models.CharField(max_length=255, verbose_name="Адрес") date_birth = models.DateField(null=True, blank=True, verbose_name="Дата рождения") class Meta: verbose_name = "Клиент" verbose_name_plural = "Клиенты" def clean(self): if self.phone: self.phone = self.phone.strip().replace(" ", "") # Remove spaces if self.phone.startswith("998") and len(self.phone) == 12: self.phone = f"+{self.phone}" elif len(self.phone) == 9 and self.phone.isdigit(): self.phone = f"+998{self.phone}" def save(self, *args, **kwargs): self.date_birth = parse_birth_date(self.pinfl) super().save(*args, **kwargs) def __str__(self): return self.inn class Device(BaseModel): OWNER_CHOICES = [ ("bank", "Банк"), … -
Django + jQuery: "Add to Cart" Button Only Works for the First Product in a Loop
I am working on a Django e-commerce website where I display multiple products using a loop in my template. Each product has an "Add to Cart" button, but the issue is that only the first product’s button works. Clicking the button on any other product does nothing. Here’s my Django view function that fetches the products: def index(request): products4 = Product.objects.filter(product_status="deal_of_the_day", featured=True) return render(request, "index.html", {"products4": products4}) My Django Template (index.html): {% for p4 in products4 %} <div class="showcase-container"> <div class="showcase"> <div class="showcase-banner"> <img src="{{ p4.image.url }}" alt="{{ p4.title }}" class="showcase-img"> </div> <div class="showcase-content"> <h3 class="showcase-title">{{ p4.title }}</h3> <p class="price">${{ p4.price }}</p> <del>${{ p4.old_price }}</del> <div class="button"> <input type="hidden" value="1" id="product-quantity"> <input type="hidden" value="{{ p4.id }}" class="product-id"> <input type="hidden" value="{{ p4.image.url }}" class="product-image"> <input type="hidden" value="{{ p4.pid }}" class="product-pid"> <span id="current-product-price" style="display: none;">{{ p4.price }}</span> <span id="product-old-price" style="display: none;">{{ p4.old_price }}</span> <button class="btn add-cart-btn" type="button" id="add-to-cart-btn">Add to Cart</button> </div> </div> </div> </div> {% endfor %} My jQuery Code (main.js): console.log("Function Index"); $("#add-to-cart-btn").on("click", function(){ let this_val = $(this); if (this_val.text() === "Go to Cart") { window.location.href = '/cart/'; return; } let quantity = $("#product-quantity").val(); let product_title = $(".product-title").val(); let product_id = $(".product-id").val(); let product_price = $("#current-product-price").text().replace(/[^0-9.]/g, ''); // Strip non-numeric characters … -
Hosting a web in local server
I built web with django, and hosted it in heroku. Now I am working for a bank and going to build dashboard, but I can not host it on heroku. It should be in the local server only as far as I know. Can someone tell how the process is, in this case? Is it required to spend long time to learn how to host? Thank you! -
Form submit confirmation does not work in jQuery `ready()`
Working in Django, I am trying to update the items of a database through submitting a form. I need a confirmation dialog before submission. These are my lines on related code: $(document).ready(function(){ setInterval(function(){ $.ajax({ type: 'GET', url: 'http://127.0.0.1:8000/update_in_line_orders', success: function(response){ $('#in-line-list').empty(); console.log('res'); let temp = "" for (let i in response.in_line_orders_list){ temp = temp + '<li>' + '<h2>' + 'Table No:' + response.in_line_orders_list[i]['table-no'] + '</h2>' + '<div>' for (let j in response.in_line_orders_list[i]['order']){ temp = temp + '<div>' + '<p class="order-item-team">' + response.in_line_orders_list[i]['order'][j]['item_title'] + '</p>' + '<p class="order-item-team">' + '........' + '</p>' + '<p class="order-item-team">' + response.in_line_orders_list[i]['order'][j]['item_quantity'] + '</p>' + '<p class="order-item-team">' + '........' + '</p>' + '<p class="order-item-team">' + response.in_line_orders_list[i]['order'][j]['item_price_rials'] + '</p>' + '</div>' } temp = temp + '</div>' + '<p class="order-item-total-team">' + 'Total' + response.in_line_orders_list[i]['total_price_rials'] + '</p>' + '<p class="date">' + response.in_line_orders_list[i]['date'] + '</p>' + '<p class="time">' + response.in_line_orders_list[i]['time'] + '</p>' + '<form id="' + String(response.in_line_orders_list[i]['order_id']) + '" method="POST">' + '{% csrf_token %}' + '<button style="font-family: Tahoma; border: none; border-radius: 20px; background-color: rgba(146,194,198,255); color: #A1662F;" name="delivered-to-table-id" value="' + response.in_line_orders_list[i]['order_id'] + '">' + 'Delivered!' + '</button>' + '</form>' + '</li>' } $("#in-line-list").append(temp) }, error: function(response){ console.log('err'); console.log(response); } }) }, 3000); }); I have tried handling the issue using … -
Gemini 2.0 experimental image generation in django
I am working on a webapp with django backend. It is related to image generation with character consistency, we finally have a model that works well for that, gemini 2.0 flash experimental. I am generating a character with openAI and then passing it as a reference to gemini via API with a prompt to generate an image. The code works perfectly in jupyter notebook, however in django, it throws an error. I am not sure how to fix it. Here is the code that works in jupyter notebook: def generate_image(request): """ Generate images using OpenAI API or Google Gemini API based on parameters """ text_prompt = request.data.get('text_prompt') use_gemini = request.data.get('use_gemini', False) character_image_url = request.data.get('character_image_url') if not text_prompt: return Response({"error": "Text prompt is required"}, status=status.HTTP_400_BAD_REQUEST) try: print(f"Generating image for prompt: {text_prompt}") print(f"Using Gemini: {use_gemini}, Character image URL: {character_image_url is not None}") # If using Gemini with a character reference if use_gemini and character_image_url: try: print(f"Generating image with Gemini: {text_prompt[:100]}...") # Download the character image response = requests.get(character_image_url) if response.status_code != 200: return Response({"error": "Failed to download character image"}, status=status.HTTP_400_BAD_REQUEST) # Load the character image into a PIL Image reference_image = Image.open(BytesIO(response.content)) # Save the reference image temporarily using standard Python tempfile … -
Django session cookies not persisting
I have a Django API which upon successful login, uses the Set-Cookie Response Headers to set a sessionId and CSRF Token in the cookies. I had it working and all of a sudden it stopped, the cookies no longer persist. After login I see them in the console, then when I refresh, they disappear. I am running my Next.js App locally with the Django API hosted on Google Cloud Run with a custom domain. Does anyone know what is going on? -
404 error on Python App deployment on CPanel
Python==3.11.11 (server ver) Django==5.1.1 Hello, today I was to deploy my app on CPanel, and everything goes fine until the end, because when configurations are all done, the page put an 404 error: Not Found The requested URL was not found on this server. Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request. I create the app. Make the MySQL database, do migrations just fine. Also changes some configurations on database, allow_hosts and static root in setting.py: from pathlib import Path import os, os.path # import dj_database_url # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('SECRET_KEY', default='your secret key') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False #ALLOWED_HOSTS = [] ALLOWED_HOSTS = ['https://sistema.juanjoserondon.com','sistema.juanjoserondon.com','www.sistema.juanjoserondon.com'] NPM_BIN_PATH = "C:/Program Files/nodejs/npm.cmd" INTERNAL_IPS = [ "127.0.0.1", ] TAILWIND_APP_NAME = 'theme' # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_browser_reload', 'phonenumber_field', 'tailwind', 'theme', 'main', 'dashboard', 'billing', 'teaching', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django_browser_reload.middleware.BrowserReloadMiddleware', ] SESSION_ENGINE = 'django.contrib.sessions.backends.db' ROOT_URLCONF = 'djangocrud.urls' PROJECT_PATH … -
What is the best way to have row-level authorization in django with some constraints?
I have a django app which consists of multiple different models. These models are related to each others with database relations. And somehow these relations are making a hierarchy. For example: Model City can have multiple Libraries Model Library can have multiple Books Now I can't have row-level permissions over single instances without their related instaces. its like having permission to view a certain book but not the library which it belongs to. So the case is I want to have a way to define a permission over city for example to see all of its libraries (but not book). And maybe to have a permission to see all libraries and books.. etc... What I though about is to have a rule-based authroization system to handle all the cases that might a rise by following a set of rules (it is somehow a smart and persisted way to do the authorization), but I was afraid that I am overwhelming and there might be a hidden package that I can use in django which solve this case efficiently.