Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Open Local Outlook Client with Attachments from Backend Using Frontend File Selection
I'm working on a web application where users can select files in the frontend, and those files are fetched from the backend. After selecting the files, I want the user's local Outlook client to open with a pre-drafted email that includes the selected attachments, allowing the user to review and send the email manually. Here’s what I’m trying to achieve: Scenario: The user selects files in the frontend. After clicking the "Send Mail" button, the local Outlook client should open with a new email, including the files (fetched from the backend) attached. Requirements: The email should be opened in the user's local Outlook client before sending (instead of being sent programmatically). Attachments should be dynamically fetched from the backend based on the user’s selection in the frontend. I am aware of how to send emails programmatically using the Microsoft Graph API, but I need a solution that opens the local Outlook client instead. I’m considering whether Outlook add-ins could help, but I haven't figured out how to pass attachments from the backend. -
401, Auth error from APNS or Web Push Service using FCM using firebase_admin
i have APNS device ID, but i got this error from when sending message def send_push_notification_legacy(device_tokens, title, body): service_account_file = os.getcwd() + '/show-coach-firebase-adminsdk-rpuoz- b40c95a3c2.json' credentials = service_account.Credentials.from_service_account_file( service_account_file, scopes=["https://www.googleapis.com/auth/firebase.messaging"] ) # Obtain an OAuth 2.0 token credentials.refresh(Request()) access_token = credentials.token url = 'https://fcm.googleapis.com/v1/projects/show-coach/messages:send' headers = { 'Authorization': f'Bearer {access_token}', 'Content-Type': 'application/json', } payload = { "message": { "token": device_tokens[0], "notification": { "title": "Breaking News", "body": "New news story available." }, } } response = requests.post(url, json=payload, headers=headers) print(response.status_code, response.json()) ERROR Details { "error" : { "code" : 401, "message" : "Auth error from APNS or Web Push Service", "status" : "UNAUTHENTICATED", "details" : [ { "@type" : "type.googleapis.com/google.firebase.fcm.v1.FcmError", "errorCode" : "THIRD_PARTY_AUTH_ERROR" }, { "@type" : "type.googleapis.com/google.firebase.fcm.v1.ApnsError" } ] } } -
How to connect custom storage to django
I am writing a custom storage module to use a remote seafile-server as storage for a django (django-cms) installation. File seafile.py is located in the project-folder: The storage class has been tested with jupyter notebook and is working. The problem: I am failing to connect my storage to django (local, development-server), it is still saving pictures local in the media-folder and not using my storage at all. In settings.py from .seafile import MyStorage ... Things I have tried: DEFAULT_FILE_STORAGE = "MyStorage" DEFAULT_FILE_STORAGE = "seafile.MyStorage" DEFAULT_FILE_STORAGE = MyStorage DEFAULT_FILE_STORAGE = MyStorage() For sure I have seen and tried the suggested solution (https://docs.djangoproject.com/en/5.1/howto/custom-file-storage/#use-your-custom-storage-engine) but failed too. What am I missing? Thank you in advance! -
How to use custom headers for passing session_id and csrf_token in Django with database-backed sessions?
I'm using Django with a database-backed session storage, and as a result, the session_id is stored in cookies. However, we're using a Caddy server that removes cookies from the request headers. I need to: Pass the session_id and csrf_token via custom headers (instead of cookies). Use these custom headers for session validation and CSRF protection in Django. Additionally, I am storing values in the session that are used to validate the request and fetch data from the session during API calls. Is it possible to configure Django to accept and validate these custom headers (session_id and csrf_token) rather than reading them from cookies? If so, how can this be achieved? Any advice or code examples would be much appreciated. Attempting to include a custom header to retrieve the session ID. -
Error while migration after installation of rest_framework_api_key
I am trying to use this library. But I am getting below error while trying to run python manage.py migrate command. Operations to perform: Apply all migrations: admin, auth, contenttypes, rest_framework_api_key, sessions Running migrations: Applying rest_framework_api_key.0001_initial... OK Applying rest_framework_api_key.0002_auto_20190529_2243...Traceback (most recent call last): File "/home/foysal/.local/lib/python3.10/site-packages/django/db/models/options.py", line 676, in get_field return self.fields_map[field_name] KeyError: 'revoked' During handling of the above exception, another exception occurred: And File "/home/foysal/.local/lib/python3.10/site-packages/django/db/models/options.py", line 678, in get_field raise FieldDoesNotExist( django.core.exceptions.FieldDoesNotExist: APIKey has no field named 'revoked' -
GET request from the Database wash away the localStorage
I am currently building "To Do" web app, using ReactJS as Frontend and Django as Backend, and use axios to fetch requests. I want a feature into my app that stores the "ToDo tasks" locally as the user updates them, and not lose it whenever the browser got refreshed or accidentally got exited. I am using hooks and useEffect to store data locally. Whenever the browser is refreshed, the local data are washed by the database. This is snippet of my code. OR you can review the code here const [taskEdits, setTaskEdits] = useState({}); useEffect(() => { const storedEdits = JSON.parse(localStorage.getItem("taskEdits")) || {}; axios .get("/tasks/") .then((res) => { const fetchedTasks = res.data; const mergedTasks = fetchedTasks.map((task) => { if (storedEdits[task.id]) { return { ...task, title: storedEdits[task.id] }; } return task; }); setTasks(mergedTasks); }) .catch((err) => console.error("Error fetching tasks:", err)); }, []); useEffect(() => { localStorage.setItem("taskEdits", JSON.stringify(taskEdits)); }, [taskEdits]); -
Running daphne in Docker without supervisor
Currently, I'm running daphne using supervisor. This is my supervisor config: [supervisord] user = root nodaemon = true [fcgi-program:daphne] socket=tcp://api:9000 directory=/home/docker/api ommand=./.docker/services/api/files/startup-operations.sh && daphne -u /run/daphne/daphne%(process_num)d.sock --fd 0 --proxy-headers main.asgi:application numprocs=2 process_name=asgi%(process_num)d autostart=true autorestart=false stdout_logfile=/dev/stdout stdout_logfile_maxbytes=0 redirect_stderr=true killasgroup=true startsecs=0 exitcodes=0 Here, the channels docs give exactly one example, and it's using supervisor: https://channels.readthedocs.io/en/latest/deploying.html However, I have read this: https://advancedweb.hu/supervisor-with-docker-lessons-learned/ ...which advocates for not using supervisor in docker, and I would agree with the article. One problem with using supervisor that the article doesn't discuss is that I have an in-memory database that I need to be available for the main application. The above config file is just one program that runs a startup-operations.sh script, but before, it used to be two programs: One program loaded the data into memory, and the other program ran the main application. Of course, I could load that data into memory in startup-operations.sh and be done with it, but that doesn't remove supervisor from my image. It seems that if I'm just running one series of commands, I should be able to not use supervisor in my image. This resulted in the first program's memory not being available to the main application. I also had … -
Submit button doesn't refresh page and send POST request
I'm doing registration on Django. I made a form, added a button that should refresh the page and send a POST request. But the button does not update the page and does not send the request. I doesn't have any scripts on JavaScript. My views.py code: `from django.shortcuts import render, redirect from .models import User from .forms import UserForm from django.views import View def index(request): return render(request, 'index.html') def inn(request): return render(request, 'in.html') class PostCreate(View): def up(self, request): form=UserForm(request.POST) if form.is_valid(): form.save() return redirect('home') def down(request): return render(request, 'up.html')` My forms.py code: `from .models import User from django.forms import ModelForm class UserForm(ModelForm): class Meta: model=User fields=['NickName', 'Email', 'Password']` And HTML: HTML I'm tried to search any information on internet, but I'm found only about event.preventDefault() and type='button'. But I doesn't have any scripts and my type is 'submit' -
Modelformset_factory including an empty list object as part of the management_form data displayed on screen
When rendering a formset created using modelformset_factory I am experiencing differing results between the local running instance of my application compared to the version running on my server. On both versions the application the files below are included the following: forms.py class NewCourseHoleForm(ModelForm): class Meta: model = CourseHole fields = [ 'hole_number', 'hole_name', 'par', 'stroke_index', 'length', ] def __init__(self, *args, **kwargs): super(NewCourseHoleForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_tag = False self.helper.form_show_errors = True self.helper.form_show_labels = False self.helper.form_class = 'form-inline' self.helper.use_custom_control = True self.helper.layout = Layout( Div( Div( Div(Field('hole_name', css_class='text-center'), css_class="col-3"), Div( Field('hole_number', css_class='d-none'), css_class="d-none"), Div(Field('length', min=50, max=800), css_class="col-3"), Div(Field('par', min=3, max=5), css_class="col-3"), Div(Field('stroke_index', min=1, max=18), css_class="col-3"), css_class='row', ), css_class='col-12' ), ) hole_formset = modelformset_factory( CourseHole, form=NewCourseHoleForm, min_num=18, max_num=18, # validate_max=True # extra=18, # can_delete=False, ) views.py class CourseDetailView(LoginRequiredMixin, DetailView): login_url = '/login/' redirect_field_name = 'redirect_to' model = Course slug_field = 'uuid' slug_url_kwarg = 'uuid' template_name = 'courses/course_detail.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) course = Course.objects.filter( uuid=self.kwargs.get('uuid')).first() context['title'] = f'{course.name} - Detail' teebox_check = CourseTeeBox.objects.filter( course=course).order_by('-course_length') context['teeboxes'] = teebox_check context['teeboxForm'] = f.NewCourseTeeBoxForm( prefix='teebox', course=course) holes = [{'hole_number': n, 'hole_name': f'Hole {n}'} for n in range(1,19)] context['holes_formset'] = f.hole_formset( queryset=CourseHole.objects.none(), prefix='holes', initial=holes) return context def get_queryset(self): queryset = super(CourseDetailView, self).get_queryset() return … -
How to change/filter option list in TreeNodeChoiceField
How to change the option/choice list of conto field, based on value gruppo_id? conto is a ForeignKey to model.ContoCOGE(MPTTModel). For each gruppo there is a tree, which develops to a certain depth. How to filter among all the tree roots and, in TreeNodeChoiceField, list only those with a group_id? In debug, formfield_for_foreignkey(self, db_field, request, **kwargs) overriden returns the correct tree. But the browser renders the page with the select field with all the trees. #model.py from mptt.models import MPTTModel, TreeForeignKey from multigroup.models import Gruppo class ContoCOGE (MPTTModel): gruppo = models.ForeignKey(Gruppo, on_delete=models.CASCADE,related_name='contoCOCGE_gruppo') parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') class PncGen (models.Model): gruppo = models.ForeignKey(Gruppo, on_delete=models.CASCADE) #other stuff class PncRighe (models.Model): gruppo = models.ForeignKey(Gruppo, on_delete=models.CASCADE) idPnc = models.ForeignKey(PncGen,on_delete=models.CASCADE) #puntatore alla testata conto = models.ForeignKey(ContoCOGE,on_delete=models.CASCADE,blank=True, null=True) #other stuff #admin.py from django_mptt_admin.admin import DjangoMpttAdmin class PncRigheInline(admin.TabularInline): model = PncRighe autocomplete_fields = ['partitarioRiga','conto'] extra = 1 def filter_tree_queryset(self, queryset,request): qs = queryset.filter(gruppo_id=int(request.session['gruppo_utente'])) return qs def get_changeform_initial_data(self, request): return {'gruppo': int(request.session['gruppo_utente'])} def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == 'gruppo' or db_field.name == 'idRiga' or db_field.name == 'idPnc': kwargs['widget'] = forms.HiddenInput() if db_field.name == 'conto': db = kwargs.get("using") qs = self.get_field_queryset(db, db_field, request) kwargs['queryset']=qs.filter(gruppo_id = request.session['gruppo_utente'] ) @admin.register(PncGen) class PncGenAdmin(admin.ModelAdmin): #... inlines = (PncRigheInline,) -
I do not receive information from the template
My footer doesn’t use any view I need to get information to save it I used parcel rendering package to render but I don’t get any information to save it even if it’s a small tip I can find it views code: def footernews(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): form.save() return render(request, 'includes/footer.html', {'myformmews': form}) else: raise ValidationError('sorry infomations dont save...') else: form = ContactForm() return render(request,'includes/footer.html',{'myformmews':form}) models code: from django.db import models class MassageNewsFoot(models.Model): email=models.EmailField(max_length=32) date=models.DateField(auto_now_add=True) def __str__(self): return f'email: {self.email}---date: {self.date}' forms code: from django import forms from home_app.models import MassageNewsFoot from django.core.exceptions import ValidationError class ContactForm(forms.ModelForm): class Meta: model = MassageNewsFoot fields = '__all__' #style form footer in widget widgets ={ 'email': forms.TextInput(attrs={'class':'form-control bordered bottom-only' ,'placeholder':'enter your email'}), } urls code: from django.urls import path from . import views app_name = 'home_app' urlpatterns = [ path("", views.Homepage.as_view(), name='home'), path("footer", views.footernews, name='footerrenderded'), ] template code: <form action="" method="post"> {% csrf_token %} <div class="subscribe-form"> <div class="head"> news this site </div> <div class="input-wrap"> {{ myformmews.email }} <button class="btn btn-primary" type="submit"> <span class="outer-wrap"> <span data-text="share"> share </span> </span> </button> </div> </form> And finally I gave it to template home: {% extends 'base.html' %} {% load static %} … -
How do i properly implement image uploads without harming the API's performance
I am currently working on a fashion marketplace app that enables designers to upload pictures of their clothes and accessories. At this stage, I'm using Django and trying to figure out how to properly implement image uploads without harming the API's performance. I am also concerned about the use of large images because of the possible repercussions in terms of user experience and costs for storage. Is it wiser to use the likes of Amazon S3 for this purpose or are there better alternatives in optimizing images on Python web frameworks? I haven't tried, I just want to know if anyone has experience of the best approach without reducing API performance -
Django cookiecutter error while trying to create a project
I'm trying to use cookiecutter for the creation of my Django projects but it is not working. My OS is: Ubuntu 24.04.1 LTS Python version: 3.12.3 I follow these steps: python3 -m venv venv source venv/bin/activate pip install Django pip install cookiecutter cookiecutter gh:cookiecutter/cookiecutter-django [1/27] project_name (My Awesome Project): car [2/27] project_slug (car): car [3/27] description (Behold My Awesome Project!): Car project [4/27] author_name (Daniel Roy Greenfeld): A V [5/27] domain_name (example.com): car.com [6/27] email (a-v@car.com): car@mail.com [7/27] version (0.1.0): 0.1.0 [8/27] Select open_source_license 1 - MIT 2 - BSD 3 - GPLv3 4 - Apache Software License 2.0 5 - Not open source Choose from [1/2/3/4/5] (1): 1 [9/27] Select username_type 1 - username 2 - email Choose from [1/2] (1): 1 [10/27] timezone (UTC): Italy [11/27] windows (n): n [12/27] Select editor 1 - None 2 - PyCharm 3 - VS Code Choose from [1/2/3] (1): 2 [13/27] use_docker (n): n [14/27] Select postgresql_version 1 - 16 2 - 15 3 - 14 4 - 13 5 - 12 Choose from [1/2/3/4/5] (1): 1 [15/27] Select cloud_provider 1 - AWS 2 - GCP 3 - Azure 4 - None Choose from [1/2/3/4] (1): 4 [16/27] Select mail_service 1 … -
Dependencies issues in docker container
I'm using a Django Based Web Application. The application is using Multiple containers which includes Redis, Postgres, ElasticSearch, Kibana and Application container. When I run "docker-compose up -d --build", all containers are started but application containers is exited, When I checked logs for this container I found this " presshook-web-app-1 | honcho start & python manage.py qcluster presshook-web-app-1 | /bin/sh: 1: honcho: not found presshook-web-app-1 | Traceback (most recent call last): presshook-web-app-1 | File "/app/manage.py", line 49, in presshook-web-app-1 | from django.core.management import execute_from_command_line presshook-web-app-1 | ModuleNotFoundError: No module named 'django' presshook-web-app-1 | make: *** [Makefile:31: run] Error 1 " I checked my requirement.in fike and it contains all the dependencies. I tried to again install them by mentioning into dockerfile. but when i run command, I still found the same error. I tried to add these packages in dockerfile manually in spite of they're also being used in requirement.in file. But I found the same issues on repeating again and again. -
Can't send mail in dockerized Django application, if email settings are set from docker environment
I'm working on dockerized django store project with Celery and Redis. When customer makes an order, Celery sends him email about it. When I set django email settings directly, everything works fine: EMAIL_USE_SSL = True EMAIL_HOST = "smtp.yandex.ru" EMAIL_HOST_USER = "mymail@yandex.ru" EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST_PASSWORD = "password" EMAIL_PORT = 465 DEFAULT_FROM_EMAIL = EMAIL_HOST_USER SERVER_EMAIL = EMAIL_HOST_USER EMAIL_ADMIN = EMAIL_HOST_USER But when I set same variables from docker-compose environment: EMAIL_USE_SSL = os.getenv("EMAIL_USER_SSL") EMAIL_HOST = os.getenv("EMAIL_HOST") EMAIL_HOST_USER = os.getenv("EMAIL_HOST_USER") EMAIL_BACKEND = os.getenv("EMAIL_BACKEND") EMAIL_HOST_PASSWORD = os.getenv("EMAIL_HOST_PASSWORD") EMAIL_PORT = os.getenv("EMAIL_PORT") DEFAULT_FROM_EMAIL = os.getenv("EMAIL_HOST_USER") SERVER_EMAIL = os.getenv("EMAIL_HOST_USER") EMAIL_ADMIN = os.getenv("EMAIL_HOST_USER") I get the following error from Celery: celery-1 | [2024-09-23 12:48:48,816: ERROR/ForkPoolWorker-2] Task orders.tasks.send_order_email[243058c7-6fc2-47a2-9f36-7e0e1b00cd9d] raised unexpected: AttributeError("'NoneType' object has no attribute 'rsplit'") celery-1 | Traceback (most recent call last): celery-1 | File "/usr/local/lib/python3.11/site-packages/celery/app/trace.py", line 453, in trace_task celery-1 | R = retval = fun(*args, **kwargs) celery-1 | ^^^^^^^^^^^^^^^^^^^^ celery-1 | File "/usr/local/lib/python3.11/site-packages/celery/app/trace.py", line 736, in __protected_call__ celery-1 | return self.run(*args, **kwargs) celery-1 | ^^^^^^^^^^^^^^^^^^^^^^^^^ celery-1 | File "/usr/src/bookstore/orders/tasks.py", line 7, in send_order_email celery-1 | send_mail( celery-1 | File "/usr/local/lib/python3.11/site-packages/django/core/mail/__init__.py", line 77, in send_mail celery-1 | connection = connection or get_connection( celery-1 | ^^^^^^^^^^^^^^^ celery-1 | File "/usr/local/lib/python3.11/site-packages/django/core/mail/__init__.py", line 51, in get_connection celery-1 | klass = … -
What is the difference between request.GET.get('username') and request.META.get('HTTP_X_ USERNAME') in DRF
I want to know the difference between this two methods of getting data Just tried to figure it out for the object concepts of this data fetching... I saw request.GET.get('username') used in customauth.py at the time of custom authentication and request.META.get('HTTP_X_ USERNAME') saw in DRF documentation where the custom authentication example is given. -
Can I create a custom client/customer end dashboard in squarespace?
So basically I am designing this website and want to deal with clients using forms submissions which I can see I can do that by create projects and invoicing from the squarespace dashboard. Send proposals and stuff like many options for me and the admin accounts but the problem is clients/customers account where there are not many options like he/she cant see the number of form submissions they did, the proposals sent to them by admins or look at the status for those proposals, invoices, previous orders submitted or rejected etc. So how can i make a proper dashboard for my clients as well to come and see all the details of services, orders, forms, proposals, previous orders etc. Currently there are only address, order option available and the order will work if I create a products page or service only can you please guide me through if there are any options where I can create a custom account dashboard for my clients as well? So like as a owner/admin I dont want to make a store as I want to sell my services through form submissions and stuff. Squarespace provides many options for admins but not much for customers … -
how to find near objects in django?
I have a service provider model . it has two fields named : lat & lon class Provider(models.Model): name = models.CharField(max_length=100) lat = models.CharField(max_length=20) lon = models.CharField(max_length=20) address = models.TextField(null=True , blank=True) def save(self, *args, **kwargs): try: data = getaddress(self.lat , self.lon) self.address = data['formatted_address'] except: pass super(Provider, self).save(*args, **kwargs) How can i get a location from user and find some service providers that are near to my user? and it must be from the lat and lon field beacuse it is possible to service provider is located on another city ! also the speed of proccesse is important! -
Generating models from old Microsoft sql server 2005 database
I am currently trying to use inspectdb to generate models from a very old Microsoft sql server 2005 database. I have not written the database. Now the error I'm getting is that 'SYSDATETIME' is not a recognized built-in function name. So I know it's because that database uses a much older function methods for time and date. How can I solve this problem thanks. -
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 … -
My request cookie not working on server but works locally (Azure Web Appservices)
I am using my web cookie from chrome to log onto a web using python requests. This works very fine on localhost http://127.0.0.1:8000/ but when I deploy this on to azure App Services, this does not work any more and shows "WARNING: Login Failed!!" class MySpider(scrapy.Spider): def __init__(self, link, text): self.link = link self.cookie = 'my_cookies' self.user_agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36' self.text = text def login(self, url): headers = { 'User-Agent': self.user_agent, 'Cookie': self.cookie, } session = requests.Session() response = session.get(url, headers=headers) response.text.encode('utf-8') if response.status_code != 200: print('WARNING: Login Failed!!') return response I tried to change cookies and inbond IP but still get WARNING: Login Failed!! -
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?