Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Login page isn't redirecting - Django
I'm trying to create a basic authentication page with user and password, and it is almost working, almost. I found that the authentication process is working but the app is failing at redirecting to the home page. Here's the code From Views def home(request): print(request.user) if request.user.is_authenticated: return render(request, "home/home.html") else: return redirect("login/") def login(request): error = '' if request.method == "POST": username = request.POST['username'] password = request.POST['password'] try: user = AppUser.objects.get(email=username) except AppUser.DoesNotExist: error = 'Usuario no encontrado' return render(request, 'login.html', {'error': error, 'form': Login()}) if hasattr(user, 'appuserauth'): if user.appuserauth.check_password(password): uauth = authenticate(request, username=user.email, password=password) if uauth is not None: login(request, uauth) return redirect("home") else: error = 'Contraseña incorrecta' return render(request, 'login.html', {'error': error, 'form': Login()}) else: error = 'El usuario no tiene una contraseña' return render(request, 'login.html', {'error': error, 'form': Login()}) else: return render(request, "login.html", { "form": Login(), "error": error }) From urls from django.urls import path from . import views urlpatterns = [ path('home/', views.home, name='home'), path('inventario/', views.inventario, name='inventario'), path('compras/', views.compras, name='compras'), path('ventas/', views.ventas, name='ventas'), path('login/', views.login, name='login'), ] Does someone know what I'm doing wrong? enter image description here Thanks I've tried changing from redirect to render, and I also tried to track the redirection. I'm … -
Django form validation errors not displaying with Bootstrap alert alert-danger styling
I'm working on a Django project where I'm using Bootstrap to style my form validation error messages. However, while the form validation works (I can see the errors in plain text), the errors are not being styled with the alert alert-danger classes from Bootstrap. I've confirmed that Bootstrap is properly included, but the error messages still appear unstyled. Here’s the relevant code from my form template: <section class="gallery" style="margin-left: 5em"> <form action="{% url 'register' %}" method="POST"> {% csrf_token %} <div class="row"> {% for field in form.visible_fields %} <div class="col-12 col-lg-12" style="margin-bottom: 10px;"> <label for="{{ field.id_for_label }}" style="color:#D9D9D9; margin-bottom: 5px;">{{ field.label }}</label> {{ field }} {% for error in field.errors %} <div class="alert alert-danger" style="margin-top: 5px;"> {{ error }} </div> {% endfor %} </div> {% endfor %} </div> <div> <button type="submit" class="btn btn-success col-12" style="padding-top: 5px;">Register</button> </div> </form> </section> Here’s what I’ve tried so far: Bootstrap inclusion: I've included the following link in my HTML file to ensure Bootstrap is loaded: <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous"> I confirmed that Bootstrap is loading by inspecting the network tab and seeing that the file is fetched without errors. Form validation: My form is correctly validating fields, and I can see errors when I … -
queryset objects in which user has an object
App has Game model and Player model. I want to get a list of the Game objects in which the logged in user has a Player. This is to show that user's Game history in a dashboard so they can see past games. This code gets all the Game objects. So it shows the history of every user. class DashboardListView(generic.ListView): model = Game template_name = 'dashboard.html' context_object_name = 'tournament_list' def get_queryset(self): return Game.objects.filter() I can narrow down to completed games for every player like this: class DashboardListView(generic.ListView): model = Game template_name = 'dashboard.html' context_object_name = 'tournament_list' def get_queryset(self): return Game.objects.filter(completed=True) I tried this to get to narrow down to only games of the specific user: def get_queryset(self): if Player.objects.filter(owner=self.request.user).exists(): mine = Player.objects.filter(owner=self.request.user).get() return Game.objects.filter( Q(player1=mine) | Q(player2=mine) | Q(player3=mine) & Q(completed=True)) But because there are multiple Player objects it throws this error: get() returned more than one Player -- it returned 12! What I want are the 12 Games in which the user has those 12 Player objects. How can I get those Game objects in which the user has a Player object? -
Why is my Avatar component not appearing on navbar?
I have been trying to get the avatar icon of user profile image to appear on the navbar but the word 'avatar' just appears instead next to 'Profile'. The Avatar icon appears perfectly fine with for my post.js I checked my API's serializer and settings, all this seems correct especially since the avatar is appearing correctly on Post.js. The API is using dj-rest-auth==6.0.0 and Django==4.2 serializers.py from dj_rest_auth.serializers import UserDetailsSerializer from rest_framework import serializers class CurrentUserSerializer(UserDetailsSerializer): profile_id = serializers.ReadOnlyField(source='profile.id') profile_image = serializers.ReadOnlyField(source='profile.image.url') class Meta(UserDetailsSerializer.Meta): fields = UserDetailsSerializer.Meta.fields + ( 'profile_id', 'profile_image' ) settings.py REST_AUTH_SERIALIZERS = { 'USER_DETAILS_SERIALIZER': 'pinch_api.serializers.CurrentUserSerializer' } Front end NavBar.js; import Avatar from './Avatar'; <NavLink className={styles.NavLink} to={`/profiles/${currentUser?.profile_id}`} > <Avatar src={currentUser?.profile_image} text="Profile" height={40} /> </NavLink> I have checked my API and searched for other solutions but I am not understanding why the avatar would appear for posts but not for navbar. Does anybody have suggestions what the problem would be? -
Django ModelDiffMixin: Maximum recursion depth exceeded
I am getting a weird error after upgrading the Django version from 4.0 to 4.2.15. The error being encountered is: RecursionError: maximum recursion depth exceeded while calling a Python object. The ModelDiffMixin looks something like below: from django.forms.models import model_to_dict class ModelDiffMixin(object): def __init__(self, *args, **kwargs): super(ModelDiffMixin, self).__init__(*args, **kwargs) self.__initial = self._dict @property def diff(self): d1 = self.__initial d2 = self._dict diffs = [(k, (v, d2[k])) for k, v in d1.items() if v != d2[k]] return dict(diffs) @property def has_changed(self): return bool(self.diff) @property def changed_fields(self): return self.diff.keys() def get_field_diff(self, field_name): """ Returns a diff for field if it's changed and None otherwise. """ return self.diff.get(field_name, None) def save(self, *args, **kwargs): """ Saves model and set initial state. """ super(ModelDiffMixin, self).save(*args, **kwargs) self.__initial = self._dict @property def _dict(self): return model_to_dict(self, fields=[field.name for field in self._meta.fields]) Referenced from the gist here: https://gist.github.com/goloveychuk/72499a7251e070742f00 Attaching the stack trace here. I have gone through the django docs as well and it seems like accessing django fields in the init method of model might cause issues. File "/Users/bm/.virtualenvs/django4.2/lib/python3.11/site-packages/django/db/models/query.py", line 122, in __iter__ obj = model_cls.from_db( ^^^^^^^^^^^^^^^^^^ File "/Users/bm/.virtualenvs/django4.2/lib/python3.11/site-packages/django/db/models/base.py", line 582, in from_db new = cls(*values) ^^^^^^^^^^^^ File "/Users/bm/.virtualenvs/django4.2/lib/python3.11/site-packages/django/db/models/base.py", line 571, in __init__ super().__init__() File "/Users/bm/Desktop/Django/bapi/core/utils.py", line … -
Install drf-api-key in django
I am trying to install drf-api-key in django. I am using Linux Mint 21.3. But I am getting below error. python3 -m pip install drf-api-key Defaulting to user installation because normal site-packages is not writeable ERROR: Could not find a version that satisfies the requirement drf-api-key (from versions: none) ERROR: No matching distribution found for drf-api-key -
Sqlite gives a value which I cannot recreate
Using django: here is some values and the query: max_played, avg_days_last_played = get_next_song_priority_values() # Calculate time since played using raw SQL time_since_played_expr = RawSQL("(julianday('now') - julianday(main_song.played_at))", []) query = Song.objects # Annotate priority songs_with_priority = query.annotate( time_since_played=ExpressionWrapper(time_since_played_expr, output_field=FloatField()), priority=( F('rating') - (F('count_played') / Value(max_played)) + (F('time_since_played') / Value(avg_days_last_played)) ), ).order_by('-priority') my logging: logger.info(f'Next Song: {next_song}') calculated_priority = ( next_song.rating - (next_song.count_played / max_played) + (next_song.time_since_played / avg_days_last_played) ) logger.info(f'Next Song: priority {next_song.priority:.2f} vs calc {calculated_priority:.2f}') logger.info(f'Next Song: rating {next_song.rating:.2f}') playd = next_song.count_played / max_played logger.info(f'Next Song: played {playd:.2f} ({next_song.count_played} / {max_played})') tspd = next_song.time_since_played / avg_days_last_played logger.info( f'Next Song: days {tspd:.2f} ({next_song.time_since_played} / {avg_days_last_played})' ) and I get: INFO Next Song: <Song-1489 End of the World Cold> INFO Next Song: priority 2.73 vs calc 2.56 INFO Next Song: rating 0.50 INFO Next Song: played 0.17 (1 / 6) INFO Next Song: days 2.23 (4.043296354357153 / 1.8125720233656466) So my calculated value is lower. All the values are there: the rating of 0.5 is solid, the play counts if 1 vs 6 is solid, the time since is used from the result next_song.time_since_played. I'm using the same values sqlite should be using, but my calc is different. -
Solr Search Not Returning Expected Results in Django with Haystack
I'm working on a Django project using Haystack for search functionality with Solr as the backend. I've set up everything, but when I perform a search, the results are not returned as expected. Problem Description I have a search view that queries Solr for products based on a search term. While the search query executes without errors, the returned results do not contain any products, even though I have verified that products exist in the database. views.py: from haystack import indexes from haystack.query import SearchQuerySet from django.shortcuts import render def search_view(request): query = request.GET.get('q') results = SearchQuerySet().filter(content=query) if query else [] print(f"Search Query: {query}, Results: {results}") context = { 'results':results, 'query':query, } return render(request, 'core/search.html', context) Search_indexes.py: from haystack import indexes from core.models import * class Solr_Model_Index (indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) def get_model(self): return Product def index_queryset(self, using=None): """Used when the entire index for model is updated.""" return self.get_model().objects.all() Steps Taken: Rebuilt the Index: I ran python manage.py rebuild_index to ensure all products are indexed. Checked Solr Admin Interface: I confirmed that products are visible in Solr under the "Documents" tab. Debugging: Added print statements in the search view to check the query and results. Current Output: Search … -
Django Channels websocket connection failed
I am working on a demo chat application as part of my learning process with Django Channels and WebSockets. My goal is to establish real-time communication using WebSockets, but I'm facing an issue where the connection to the WebSocket fails. In the browser console, I consistently see an error message indicating that the WebSocket connection could not be established. Despite setting up the necessary consumers, routing, and ASGI configurations, the WebSocket connection doesn't seem to go through, and I'm unable to proceed with the real-time messaging functionality. In the console it shows me: WebSocket connection to 'ws://127.0.0.1:8000/ws/friends/' failed: (anonymous) @ friends/:12 This is my consumers.py file from channels.layers import get_channel_layer from channels.generic.websocket import AsyncWebsocketConsumer class ChatConsumer(AsyncWebsocketConsumer): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.channel_layer = get_channel_layer() async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat%s' % self.room_name await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) This is my routing.py file from django.urls import path from . import consumers websocket_urlpatterns = [ path('ws/<str:room_name>/',consumers.ChatConsumer.as_asgi()) ] and my asgi.py file import os from django.core.asgi import get_asgi_application from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter,URLRouter import chatapp.routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') application = ProtocolTypeRouter({ 'http':get_asgi_application(), 'websocket':AuthMiddlewareStack( URLRouter( chatapp.routing.websocket_urlpatterns ) … -
Django File Upload Not Working: Media File Missing and Full Path Issue
I'm working on a Django project where I'm trying to handle file uploads, but I'm encountering some issues. The uploaded files are missing, and I don't have the full path to the media files. Here's what I've done so far: Models I have a model with a FileField for uploads: class Article(TrackingModel): titleArt = models.CharField(max_length=200) descriptionArt = models.TextField() content = models.FileField(upload_to='articles/%Y/%m/%d') section = models.ForeignKey(Section, on_delete=models.CASCADE) is_accepted = models.BooleanField(default=False) created_by = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.titleArt Settings I'm using the following settings for media files: MEDIA_ROOT = BASE_DIR / 'media' MEDIA_URL = 'media/' URLs I've set up the URL patterns like this: from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('ciems_administration/', include('administration.urls')), path('auth/', include('accounts.urls')), path('', include('intelsight.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Template Here's a snippet of the template where I show the file details: <div class="container"> <h1>Report Details</h1> {{ article.titleArt }}<br> {{ article.descriptionArt }}<br> {{ article.content.url }}<br> {{ article.section }}<br> {{ article.created_at }}<br> {{ article.updated_at }}<br> <a href="{% url 'articleList' %}" class="btn btn-primary">Back</a> </div>[![enter image description here](https://i.sstatic.net/O9jkZnK1.jpg)](https://i.sstatic.net/O9jkZnK1.jpg) Problem The uploaded file paths are shown as /media/..., but the files are not actually present in the media directory. The file upload doesn't seem to … -
Running `collecstatic` returns [Errno 13] Permission denied in docker compose
I run my django app in Docker. I recently tried running collecstatic and instead was given this error code: >docker-compose exec web python manage.py collectstatic Traceback (most recent call last): File "/code/manage.py", line 22, in <module> main() File "/code/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.11/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() ... PermissionError: [Errno 13] Permission denied: '/code/static/admin/img/tooltag-arrowright.bbfb788a849e.svg.gz' I added a USER at the end of my Dockerfile so that the USER isn't root which I know is a security vulnerability. Here is my Dockerfile: # Pull base image FROM python:3.11.4-slim-bullseye # Set environment variables ENV PIP_NO_CACHE_DIR off ENV PIP_DISABLE_PIP_VERSION_CHECK 1 ENV PYTHONUNBUFFERED 1 ENV PYTHONDONTWRITEBYTECODE 1 ENV COLUMNS 80 #install Debian and other dependencies that are required to run python apps(eg. git, python-magic). RUN apt-get update \ && apt-get install -y --force-yes python3-pip ffmpeg git libmagic-dev libpq-dev gcc \ && rm -rf /var/lib/apt/lists/* # Set working directory for Docker image WORKDIR /code/ # Install dependencies COPY requirements.txt . RUN pip install -r requirements.txt # Copy project COPY . . # Create a custom non-root user RUN useradd -m example-user # Grant necessary permissions to write directories and to user 'example-user' RUN mkdir -p /code/media /code/static && \ chown -R … -
Is it possible to have a child model with multiple parents in a Django App?
I am creating a quiz back-end. I would like to add a feature where a user can report a question for being irrelevant or not fair. I have 3 relevant models for this in my Django app: User Model Question Model Report Model I would like to record what user created the report and also what question was reported. Is it possible to have a Many to 1 relationship between Report:User and also a Many to 1 relationship between Report:Question too? The report model would have two parents - User and Question. Is there a better way of doing this? -
creating reports in arabic with django
iam trying to create a report using django but the arabic word coes out redacted for some reason this is the and example of the pdf this is my view function this function and templates works just fine with downloading the pdf but when it comes out to rendering arabic it does't work i have downloaded this arabic font NotoKufiArabic-VariableFont_wght.ttf but it won't work for some reason from django.http import HttpResponse from django.template.loader import get_template from xhtml2pdf import pisa from io import BytesIO from django.shortcuts import get_object_or_404 from ..models import Supplier, TransactionModel from django.db.models import Sum def generate_pdf_report(request, supplier_name): supplier = get_object_or_404(Supplier, supplier_name=supplier_name) transactions = TransactionModel.objects.filter(supplier_name=supplier).order_by('payment_date') total_paid = transactions.aggregate(Sum('payment_amount'))['payment_amount__sum'] or 0 remaining_amount = supplier.total_amount - total_paid context = { 'supplier': supplier, 'transactions': transactions, 'total_paid': total_paid, 'remaining_amount': remaining_amount, } template = get_template('supplier_report.html') html = template.render(context) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), result, encoding='UTF-8') if not pdf.err: response = HttpResponse(result.getvalue(), content_type='application/pdf') response['Content-Disposition'] = f'attachment; filename="{supplier_name}_report.pdf"' return response return HttpResponse('Error generating PDF', status=400) and this is my template <html lang="ar" dir="rtl"> <head> <meta charset="UTF-8"> <title>تقرير المورد - {{ supplier.supplier_name }}</title> <style> @font-face { font-family: 'Arabic Font'; src: url('../../NotoKufiArabic-VariableFont_wght.ttf') format('truetype'); } body { font-family: 'ArialArabic', Arial, sans-serif; direction: rtl; text-align: right; } table { … -
Loading Css in django template
Using Django template, i made some HTML files and one base.html, while I'm in local, there are zero issues, everything loads perfectly, while I'm production however, the base.html css won't load, everything else loads, images , js, and even the css of other stuff ( i ran collectstatic ) but this particular one doe not load, i load it up using tags <link rel="stylesheet" href={% static "css/style.css" %} exactly like this in other templates, all the css files are inside a folder called ***/public_html/static/css and in my settings.py, i have this line STATIC_ROOT = '/somepath/public_html/static' after running collectstatic, Django put all of my img, css,js and vids and put them inside this folder so : /somepath/public_html/static/ |img/ |vid/ |css/ |js/ what am i doing wrong? why every things load properly including all the img and css but the css of Django templatebase.html doesn't ? base.html is the template file that most template extend from it using Django template extend feature. So far i haven't tried anything special, if i load the css manually, it works, it just that when i extend the html using Django template it doesn't, I'm using Django version 3.x.x however and not the latest one on … -
Azure AppService with Django on Linux using Azure Devops for CI takes 20 minutes
I am using Django on Linux with Azure Devops as Continuous Integration / Continuous Development purposes. I have succesfully setup the yaml file for deployment and associated with Azure AppService which seems to be working ok. However it takes a long time ( about 20 minutes ), it was a lot faster with other cloud providers ( such as 3-4 minutes ) Here below is my azure-pipelines-prod.yaml file : # Python to Linux Web App on Azure # Build your Python project and deploy it to Azure as a Linux Web App. # Change python version to one thats appropriate for your application. # https://docs.microsoft.com/azure/devops/pipelines/languages/python trigger: - main variables: # Azure Resource Manager connection created during pipeline creation azureServiceConnectionId: 'xxxxxxxx-7f93-4dc6-922b-ae9b29311fbf' # Web app name webAppName: 'project-app' # Agent VM image name vmImageName: 'ubuntu-latest' # Environment name environmentName: 'project-app' # Project root folder. Point to the folder containing manage.py file. projectRoot: $(System.DefaultWorkingDirectory) pythonVersion: '3.9' stages: - stage: Build displayName: Build stage jobs: - job: BuildJob pool: vmImage: $(vmImageName) steps: - task: UsePythonVersion@0 inputs: versionSpec: '$(pythonVersion)' displayName: 'Use Python $(pythonVersion)' - script: | python -m venv antenv source antenv/bin/activate python -m pip install --upgrade pip pip install setup pip install --target="./antenv/lib/python3.9/site-packages" -r … -
Front-end development failed to introduce css
When using Django, the front end successfully introduces css, but does not display on the pageenter image description here The python version is OK, the development framework is OK, the css writing is OK, the css is confirmed to have been successfully introduced, and the css path is OK。 -
Django not connecting to proper DB [closed]
I'm building a rather small backend component with Django and I got it connected to an external Postgre DB. The issue is, when I started the Django app and tried to fetch some data all I got is a 204 No content response (which is what I'd expect if there is no data in DB) but the DB has data, which make me think my app is not connecting to the proper DB. This is my DB config which was working before and is working in my deployed component: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.environ.get('DATABASE_NAME'), 'USER': os.environ.get('DATABASE_USERNAME'), 'PASSWORD': os.environ.get('DATABASE_PASSWORD'), 'HOST': os.environ.get('DATABASE_HOST'), 'PORT': os.environ.get('DATABASE_PORT'), } } There is no error showing up at all, just my DB has some test data which I can access through pgAdmin (pgAdmin result) and I also can get the data through postman calling the current deployed component (GET /api/products/ HTTP/1.1" 200 899 "-" "PostmanRuntime/7.41.0"/) -
Django as_field_group?
How can I modify the as_field_group method to change the order of its returned values? Currently, the method returns the label, error message, and then the input field. However, I want to customize it so that it returns the label first, then the input field, and finally the error message at the end. How can I either override or customize the as_field_group method to achieve this? -
How to retrieve filtered queryset used to render form fields in Django?
I have a Django form that contains a table with rows that reflect course objects from a database . Each row contains a checkbox input. This form also has some submit buttons that allow the user to filter the course objects shown in the table (besides a generic submit button). This form is used to update the users profile with courses they are interested in. When the form is submitted, courses in the filter that are unchecked should be removed from the interested M2M relation and checked ones should be added to it. To do that I need to know which inputs are checked , which I know how to retrieve, but I also need to know which courses are in the table that have unchecked inputs. Retreiving this is not as easy as ‘all the other courses in the database’ because my table does not always contain all course objects. If a user previously clicked one of the filter buttons, then the table contains only a filtered set of courses. So I need to know which courses were used to create the table at rendertime, i.e. the ones that were injected as HTML context variable. Of course I know … -
Django app with Amazon RDS works fine in localhost, but after deployed on Elastic Beanstalk unable to get data from RDS
This is a tutorial project available on w3schools. My app can access and update PostgreSQL database stored in amazon RDS while running in local virtual environment. I deployed the project on Elastic Beanstalk. It opens and shows the pages as it should, but when database involves keep-on loading and throughs "504 Gateway Time-out". Database : PostgreSQL app link : http://mydjangoapp-env.eba-mppp6a3b.ap-south-1.elasticbeanstalk.com/ source-code : https://github.com/jyotiskaborah/my_tennis_club.git I tried to check my settings.py file no error found. Please help me to fix this issue. I guess there is some permission related settings which causing this error. -
how to configure nginx so that front end and backend works in AWS
i am deploying my app on AWS instance. i have both frontend and backend as docker image. i want to use nginx. when i run this config, and go to AWS given public URL, then 502 is returned by nginx. /api /docs they are working but /admin / returning 502. here is my conf files: docker-compose.yml: backend: container_name: backend image: ${BACKEND_IMAGE_NAME}:${IMAGE_TAG} command: python manage.py runserver 0.0.0.0:8000 env_file: - .env expose: - 8000 frontend: container_name: frontend image: ${FRONTEND_IMAGE_NAME}:${IMAGE_TAG} expose: - 3002 env_file: - .env nginx: build: ./nginx ports: - 80:80 depends_on: - backend - frontend here is nginx conf: upstream backend { server backend:8000; } upstream frontend { server frontend:3002; } server { listen 80; location /api/ { proxy_pass http://backend; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /docs/ { proxy_pass http://backend; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /admin/ { proxy_pass http://backend; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location / { proxy_pass http://frontend; # Proxy to frontend on port 3002 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; # Ensure that Nginx handles large files and requests well client_max_body_size 100M; # Timeout settings to prevent 502 Bad Gateway proxy_connect_timeout 600; proxy_send_timeout 600; … -
How to customize Django Oscar category_tree template tag and remove pk from category URLs?
I'm working on an eCommerce project using Django Oscar, and I've run into an issue that I can't seem to solve. My goal is to customize the category URLs to only use slugs instead of both slug and pk, but I'm having trouble implementing this. Here's what I've done so far: What I Want to Achieve: I want to remove the pk from the category URLs in Django Oscar. Right now, my URLs look like this: http://127.0.0.1:8000/category/metal-detectors_2/ I would like them to look like this: http://127.0.0.1:8000/metal-detectors/ My Setup: I'm using a forked catalogue app from Django Oscar, where I'm making my customizations. I have a custom template categories.html in which I am trying to loop through categories and their child categories. I have created a custom template tag category_tree in a templatetags folder under the catalogue app to handle category rendering. Problem: I am using the {% category_tree as tree_categories %} template tag to render categories, but it seems to be failing due to the use of pk in the URL construction. I want to modify it to only rely on the category_slug. However, I keep getting the following error: NoReverseMatch: Reverse for 'category' with keyword arguments '{'category_slug': 'metal-detectors', 'pk': … -
FOREIGN KEY constraint failed in Django Python
I am trying to make a cabbie accept accept a ride but couldn't. FOREIGN KEY constraint fail Ride is available to accept when it is created and is in temporary phase While accepting the cabbie and his vehicle will be assigned to ride But Foreign Key constraint fails Model: class Ride(models.Model): STATUS_CHOICES = [ ('Temporary', 'Temporary'), ('Passenger Confirmed', 'Passenger Confirmed'), ('Cabbie Confirmed', 'Cabbie Confirmed'), ('Cancelled', 'Cancelled'), ('Completed', 'Completed'), ] pick_up = models.ForeignKey(Location, on_delete=models.PROTECT, related_name='pick_up') drop = models.ForeignKey(Location, on_delete=models.PROTECT, related_name='drop') distance = models.DecimalField(decimal_places=2, max_digits=7) fare = models.DecimalField(decimal_places=2, max_digits=7) passenger = models.ForeignKey(User, on_delete=models.PROTECT, related_name='rides') cabbie = models.ForeignKey(User, on_delete=models.PROTECT, related_name='driven_rides', null=True, blank=True) vehicle_type = models.ForeignKey(VehicleType, on_delete=models.PROTECT, related_name='rides', null=True, blank=True) vehicle = models.ForeignKey(Vehicle, on_delete=models.PROTECT, related_name='rides', null=True, blank=True) status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='Temporary') accepted_at = models.DateTimeField(null=True, blank=True) completed_at = models.DateTimeField(null=True, blank=True) def calculate_fare(self): return (self.distance * self.vehicle_type.farekm) + self.vehicle_type.charges def __str__(self): return f"Ride from {self.pick_up} to {self.drop} - Status: {self.status}" View: def accept_ride(request, ride_id): # Fetch the ride object or return 404 if not found ride = get_object_or_404(Ride, id=ride_id) # Check if the user is a Cabbie if not request.user.groups.filter(name='Cabbie').exists(): messages.error(request, "You must be a cabbie to accept this ride.") logger.info(f"User {request.user.username} attempted to accept a ride but is not a cabbie.") return redirect('CabbieDashboard') if … -
How to configure two server domains in django-anymail
I'm working on a Django project and using Anymail with Mailgun to send emails. I have two domains pointing to same site domain1.com and domain2.com I set up mailgun both senver domains as mg.domain1.com and mg.domain2.com both with their api key. Both domains worked fine when set as default domain senders. I need to send client email and switch them depending if they are users of domain1 or domain2. Because I want the serder email will be noreply@domain1.com and noreply@domain2.com depending on the user. In my settings.py, I have the following configuration: ANYMAIL = { 'MAILGUN_API_KEY': API_KEY_DOMAIN1, 'MAILGUN_SENDER_DOMAIN': SENDER_DOMAIN_1'], } EMAIL_BACKEND = 'anymail.backends.mailgun.EmailBackend' SERVER_EMAIL = noreply@domain1.com DEFAULT_FROM_EMAIL = Domain 1 <noreply@domain1.com> Here is send email code: email = AnymailMessage( to=message.to.split(','), cc=message.cc.split(',') if message.cc else None, bcc=message.bcc.split(',') if message.bcc else None, reply_to=None, subject=message.notification.subject, body=message.notification.body_text, from_email=message.from_email, ) email.attach_alternative(message.notification.body_html, 'text/html') if user.brand['name'] == 'domain2': email.esp_extra = { 'sender_domain': SENDER_DOMAIN_2, 'api_key': API_KEY_DOMAIN2, } try: email.send() except Exception as e: print('Error sending email:', e) As you can see. I try to use esp_extra to switch between sender domain, but I get: anymail.exceptions.AnymailRequestsAPIError: Mailgun API response 401 (Unauthorized): 'Forbidden' What could be causing this issue, and how can I resolve it? -
Video Not Displaying on Vercel Deployment in Django Project (Works Locally)
I'm working on a Django project where I'm displaying a video using the tag. The video works perfectly on my local development server, but once I deploy the project to Vercel, the video does not load. Here’s the HTML code I’m using to display the video: I tried using both {{ video_url }} and the {% static %} tag to load the video file from the static/videos directory. I also ensured the video file was collected using collectstatic and updated the vercel.json file to serve static files correctly. I expected the video to load and play as it does on the local development server. However, after deploying to Vercel, the video doesn’t show up at all. No error messages are shown in the browser console.