Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django uwsgi: Server Error (500) - while accessing view model without "q" parameter
I started facing an issue since upgrading my server from Ubuntu 18.04 LTS to Ubuntu 20.04 LTS. It seems that I'm encountering an issue (Server Error (500)) with only one model, specifically with the URI /admin/mymodule/mymodel/. Please refer uwsgi logs below: [pid: 27771|app: 0|req: 4/8] 192.168.1.101 () {72 vars in 1623 bytes} [Fri May 26 06:11:11 2023] GET /admin/mymodule/mymodel/ => generated 145 bytes in 210 msecs (HTTP/1.1 500) 6 headers in 184 bytes (1 switches on core 0) But when trying the same URI with query parameter (/admin/mymodule/mymodel/?all=&q=2022-12-19), it is working fine. Please refer uwsgi logs below: [pid: 27768|app: 0|req: 3/9] 192.168.1.101 () {70 vars in 1627 bytes} [Fri May 26 06:11:15 2023] GET /admin/mymodule/mymodel/?all=&q=2022-12-19 => generated 100205 bytes in 1013 msecs (HTTP/1.1 200) 9 headers in 463 bytes (1 switches on core 0) [pid: 27770|app: 0|req: 3/10] 192.168.1.101 () {68 vars in 1468 bytes} [Fri May 26 06:11:16 2023] GET /admin/jsi18n/ => generated 3187 bytes in 12 msecs (HTTP/1.1 200) 6 headers in 189 bytes (1 switches on core 0) I don't understand the behavior as I'm able to access all other view models and custom views successfully without any issues. And able to access this view with any … -
Retrieve bank account number through plaid in Django
I am creating a financial app using django. I want a user can connect to any bank using Plaid and on the UI, I want to see the bank account number and balance. I am not sure how to retrieve the dummy bank account number I tried to connect to any bank using Plaid and I did that successfully. I have my account id and access token -
custom django sub-admin custom permission provided by admin
I have a django custom django admin panel and now i have create a new app where admin will be able to register sub admin once subadmin is registered he will get into another app where he has to select the sub admin from the drop down and will see the different app name with two option read or rea/write admin has to select one and that specific app with that select permission will be allocated the subadmin Pleas let me know how i can achieve this -
Django - Function Based View update record - error - Record Already exists
I am trying to update an existing record using Django 4.2, Crispy Forms, and Function Based View. The field currency_code in the table Currency is used as a ForeignKey in another table(s). I cannot update the currency record without getting the message that the record already exists. Below is the code and screenshot: MODELS.PY: class Currency(models.Model): currency_code = models.CharField(max_length=3) currency_name = models.CharField(max_length=80) class Meta: verbose_name_plural = "Currencies" def __str__(self): return self.currency_code class Forex(models.Model): currency_code = models.ForeignKey(Currency, on_delete=models.CASCADE) forex_rate = models.DecimalField(max_digits=8, decimal_places=4) last_updated_on = models.DateTimeField(auto_now=True) class Meta: verbose_name_plural = "Forex Rates" def __str__(self): return self.currency_code.currency_code FORMS.PY: class UpperCase(forms.CharField): def to_python(self,value): if value: return value.upper() class CurrencyForm(forms.ModelForm): currency_code = UpperCase(label='Currency Code', min_length=3, max_length=3, error_messages={'required': 'Currency Code Cannot Be Blank'}, required=True) currency_name = UpperCase(label='Currency Name', min_length=5, max_length=80, error_messages={'required': 'Currency Name Cannot Be Blank'}, required=True) class Meta: model = Currency fields = ['currency_code', 'currency_name'] # Method 2 for checking duplicates working ok def clean_currency_code(self): currency_code = self.cleaned_data.get('currency_code') if Currency.objects.filter(currency_code=currency_code).exists(): raise forms.ValidationError('Currency Code {} already exists!'.format(currency_code)) return currency_code VIEWS.PY: def currency_edit(request, id): obj = Currency.objects.get(id=id) if request.method == 'POST': form = CurrencyForm(data=request.POST, instance=obj) if form.is_valid(): form.save() return redirect('currency_list_page') else: form = CurrencyForm(instance=obj) return render(request, 'main/currency_edit.html', locals()) CURRENCY_EDIT.HTML <form action="{% url 'currency_edit_page' id %}" class="row g-3 … -
Is there the parameter to pass a billing address to "Payments" on Stripe Dashboard after a payment on Stripe Checkout?
I'm trying to pass a billing address to Payments on Stripe Dashboard but I couldn't find the parameter to do it in payment_intent_data. So instead, I used payment_intent_data.metadata as shown below. *I use Django: # "views.py" from django.shortcuts import redirect import stripe checkout_session = stripe.checkout.Session.create( line_items=[ { "price_data": { "currency": "USD", "unit_amount_decimal": 1000, "product_data": { "name": "T-shirt" }, }, "quantity": 2 } ], payment_intent_data={ "shipping":{ "name": "John Smith", "phone": "14153758094", "address":{ "country": "USA", "state": "California", "city": "San Francisco", "line1": "58 Middle Point Rd", "line2": "", "postal_code": "94124" } }, "metadata":{ # Here "name": "Anna Brown", "phone": "19058365484", "country": "Canada", "state": "Ontario", "city": "Newmarket", "line1": "3130 Leslie Street", "line2": "", "postal_code": "L3Y 2A3" } }, mode='payment', success_url='http://localhost:8000', cancel_url='http://localhost:8000' ) return redirect(checkout_session.url, code=303) Then, I could pass a billing address to Payments on Stripe Dashboard as shown below, but if there is the parameter to pass a billing address to Payments on Stripe Dashboard, it is really useful: I know that there are address parameter when creating a customer and address parameter when updating a customer but both address doesn't have name and phone parameters. # "views.py" from django.shortcuts import redirect import stripe def test(request): customer = stripe.Customer.search(query="email:'test@gmail.com'", limit=1) shipping={ "name": "John … -
Django cant link user to profile page from login
I have been trying to make a redirect link for the login of my django site, its supposed to take the user back to their profile page once they hit the login button, im trying to identify the user based on their id, which is defined in the models section, but for some reason it wont let me reference it by id, which is weird because it lets me do this for updating, and also viewing specific profiles sign in form {% extends 'base.html' %} {% block content %} <main class="form-signin w-100 m-auto"> <form action='<int:id>/' method='GET'> {{form.as_p}} <input type='Submit' value='Save ' /> </form> </main> {% endblock %} Models form where the id is defined from django.db import models from django import forms from django.utils.formats import date_format import datetime from datetime import date, timedelta from django.urls import reverse # Create your models here. class User(models.Model): GENDERS = [ ("F","FeMale"), ("M","Male"), ("O","Other"), ("N/A","Choose not to identify"), ("AH!","Attack Helicopter"), ] email = models.CharField(max_length=30,default=False) username = models.CharField(max_length=30,default=False) password = models.CharField(max_length=30,default=False) remember_login= models.BooleanField(blank=True) FA2 = models.BooleanField(default=False) dob = models.CharField(max_length=30) gender = models.CharField(max_length=4, choices=GENDERS) def get_absolute_url(self): return reverse("users:user-profile", kwargs={"id":self.id}) #could make a list of users to reference based on id, but this would prob be visible … -
blog post image slideshow
What I've got in my mind is that there is a blog section on my Django website. there are posts in this blog section. every post has a main photo. when you click on the main photo and post summary you can see more about that post. in the post details, there is a photo slide show which shows a couple of photos from the database. I defined my model like this: model.py: from django.db import models from django.contrib.auth.models import User class Post(models.Model): author = models.ForeignKey(User, on_delete=models.DO_NOTHING, null=True) image = models.ImageField(upload_to='blog_images/', default='blog_images/default.jpg') title = models.CharField(max_length=255) content = models.TextField() status = models.BooleanField(default=False) def __str__(self) -> str: return self.title class Images(models.Model): post = models.ForeignKey(Post, default=None, on_delete=models.CASCADE) images = models.ImageField(upload_to='blog_images/', default='blog_images/default.jpg') and of course, we have admin site settings. admin.py: from django.contrib import admin from .models import Post, Images class ImagesAdmin(admin.StackedInline): model = Images @admin.register(Post) class PostAdmin(admin.ModelAdmin): inlines = [ImagesAdmin] list_display = ('title',) admin.site.register(Images) at last, we have views! views.py: from django.shortcuts import render from blog.models import Post, Images def blog_single(request, **kwargs): posts = Post.objects.filter(status=1) if pid := kwargs.get('pid'): post = posts.get(id=pid) images = Images.objects.filter(post__id=post.id) context = {'post':post, 'images':images} return render(request, 'blog/blog-single.html', context) The problem is that I cannot find a way to … -
Wagtail error that 'wagtail.models.i18n.Locale' is not in installed apps
I'm attempting to upgrade from Wagtail 4.1 LTS to 5.0. I've paid attention to the documentation and the upgrade considerations, and changed all my import statements and models accordingly. I wasn't using any localization support other than anything enabled by default, for example, I didn't have WAGTAIL_I18N_ENABLED in my settings.py When I attempt to makemigrations I am getting the error that RuntimeError: Model class wagtail.models.i18n.Locale doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. I am unsure how to resolve this as I am not using anything to do with localization, and I can't see anything relating to it in upgrade considerations. The error seems to be coming from files specific to wagtail base code and not any of my applications. What steps can I take to troubleshoot and resolve this? -
How to implement update mechanism in my django/django rest framework project
I’m trying to do an app which is able to get data from other websites and get updated itself without handling from the user. For instance: when it is 2pm my script is launched in my app, it gets data, then my database is updated by using my model and serializers/forms. Do you have an idea that is it possible to do it on a django project? Thanks for all! -
Silk UI not loading: ERROR CODE 103 - Enable JavaScript to run this app
I'm experiencing an issue while trying to access the Silk statistics for my Django app. When I request the corresponding URL (http://localhost:8000/silk/), I'm getting the following response: ERROR CODE 103: You need to enable JavaScript to run this app. Interestingly, instead of showing the Silk UI, it displays the UI of my React app, which makes API calls to the Django app. In my Django Settings.py file, I have the Silk middleware configured as follows: MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', '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', 'silk.middleware.SilkyMiddleware', ] Furthermore, I can confirm that Silk operations are being logged in the console, indicating that data is being successfully recorded in the database. I think that this tool would be very useful for me to be able to do an analysis of the performance of my Django app, but until now I have not been able to make it work completely. Any help, thanks in advance! -
on_connect() missing 3 required positional arguments: 'userdata', 'flags', and 'rc'
I am writing a django application which should act as MQTT publisher and as a subscriber. but when i run it , it give me: TypeError at / on_connect() missing 3 required positional arguments: 'userdata', 'flags', and 'rc' this is my code : from django.shortcuts import render from .models import Video from .form import VideoForm import paho.mqtt.client as mqtt from django.http import HttpResponse import time def on_connect(client, userdata, flags, rc): print("Connected with result code "+str(rc)) client.subscribe("a") #global result def on_message(client, userdata, msg): global result result = msg.payload.decode("") print("Received message:", result) client = mqtt.Client("p1") client.connect("127.0.0.1", 1883) client.publish("test", 'C:/Users/HP/Desktop/NV_4.mp4') client.on_connect = on_connect client.on_message = on_message -
Vue.Js Routing issues, when visiting product and Visit other links after that, links stack one on top of another
I am building an E-Commerce with Vue.js and Django Rest Framework. Everything is working fine, the only problem is that when I press and visit a product page, then open menu and press any other link it sends me to a blank page and then stacks slug on top of another slug or like link on top of another link which breaks the view. Lets imagine we visit "lechuga crespa" and then press in menu on "products" it will send you to a blank view and the link would be like that: :8000/lechuga-crespa-verde/productos when it should replace /lechuga-crespa/ by /productos/. How could I solve that? Thank you. Here is my router.js: import { createRouter, createWebHistory } from 'vue-router' import store from '../store' import axios from 'axios' import Home from '../views/Home.vue' import Products from '../views/shop/Products.vue' import Product from '../views/shop/Product.vue' import About from '../views/About.vue' import Corporate from '../views/Corporate.vue' import Contact from '../views/Contact.vue' import ContactThankYou from '../views/ContactThankYou.vue' import Login from '../views/auth/Login.vue' import SignUp from '../views/auth/SignUp.vue' import ResetPassword from '../views/auth/ResetPassword.vue' import ResetPasswordToken from '../views/auth/ResetPasswordToken.vue' import ResetPasswordMessage from '../views/auth/ResetPasswordMessage.vue' import ResetSetNewPassword from '../views/auth/ResetSetNewPassword.vue' import Account from '../views/auth/Account.vue' import ComplaintsBook from '../views/ComplaintsBook.vue' import PrivacyPolicy from '../views/PrivacyPolicy.vue' import Favorites from '../views/Favorites.vue' import Cart from '../views/shop/Cart.vue' import Checkout … -
Django validation (Django Rest Framework) doesn't work with parallel queries
In my DRF Film serializer I have general validate() method: def validate(self, data): request = self.context.get('request') existing_film = Film.objects.filter(title__iexact=data.get('title'), release_date=data.get('release_date'), director__iexact=data.get('director')) if request.method == 'POST': if existing_film: validation_error_message = 'Film with such parameters (title, director, release date) already exists' logger.warning(f'Validation error - {validation_error_message}') raise serializers.ValidationError(validation_error_message) return data As you can see, it makes request to the database and compares posted film with the existing one. Everything works well when queries are sequential. But if I try to make parallel queries (for example, from two terminal windows) validate() doesn't work properly and both identical films are being pushed to the database, which is definitely not what I expect. Should I use some sort of transactions or something? Thank you! -
React/Django/Redux 400 Bad Request when registering a new user
I've been struggling with this error for a while now. Pretty new to python, Django and Redux so trying to solve this has been a struggle. I've been trying to register a new user through my react frontend but the console gives me a 400 (Bad Request). I'm able to make new users through Django admin, but can't through my frontend register page. I have no idea if my frontend or backend is the issue. Any help would be appreciated RegisterPage.js import React, { useEffect, useState } from "react"; import { Link, useLocation, useNavigate } from "react-router-dom"; import { Form, Button, Row, Col } from "react-bootstrap"; import { useDispatch, useSelector } from "react-redux"; import Loading from "../components/Loading"; import ErrorMessage from "../components/Error"; import FormContainer from "../components/FormContainer"; import { login, register } from "../actions/userActions"; import axios from "axios"; function RegisterPage() { const [first_name, setFirst_name] = useState(""); const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const [confirmPassword, setConfirmPassword] = useState(""); const [errorMessage, setErrorMessage] = useState(""); const location = useLocation(); const navigate = useNavigate(); const dispatch = useDispatch(); const redirect = location.state ? Number(location.state) : "/"; const userRegister = useSelector((state) => state.userRegister); const { error, loading, userInfo } = userRegister; const submitHandler … -
Django how to get the values with an id as key and shows it in template
I have got a DICT like this: {4: {'26.00': "{'tac': {'4.99': '1.30'}}"}, 2: {'32.00': "{'tac': {'4.99': '1.60'}}"}} Where 4 and 2 are the respective user id. I send the DICT to template and I also have access to the user id in a for loop. Is it possible to get only the data to the respsctive user in the template: I would like to learn a workout to get the dict data for each user by user.id. Is it possible to do something like this? Remembering that the DICT isnt inside any model. So it is a static data generated before the tamplate renders. user_name: John user_email: j@j.com user_id = 2 amount = 32.00 tac = 4.99 : 1.60 user_name: Charles user_email: c@c.com user_id = 4 amount = 26.00 tac = 4.99 : 1.3 Thank you very much for any ideas os directions to solve it. -
Interval callback is interrupting download callback in Dash. Is there a way to stop this?
I have an app built using django-plotly-dash in a container. The app uses an interval callback to periodically check the container for new files that are added from a backend process and update the frontend with said files. There is also a callback to download the file from the container. I've noticed when downloading a file, the interval callback is hammering away and interrupting the download callback. When the interval callback is disabled, the download works fine. I've disabled the interval callback and replaced it with a manual refresh button for the time being. It's currently satisfying the client's needs, but they would like it to automatically update instead of pressing "Refresh" until the files appear. Can anyone point me in the right direction on how to go about this issue? -
No module named 'django' | Django installed | Python 3 | No virtual env
I am trying to use Django Models in another python script script.py. This is my script from os import environ environ['DJANGO_SETTINGS_MODULE'] = 'settings' import sys sys.path.append("C:/.../djangoproject/djangoproject") from settings import * sys.path.append("C:/.../djangoproject/myapp") from models import video vid = video(video_title='a title') vid.save() This is my folder structure: djangoproject _script.py _djangoproject: __settings.py __ ... _myapp __models.py __ ... This is the error Traceback (most recent call last): File "C:\...\djangoproject\script.py", line 11, in <module> from models import video File "C:\...\djangoproject/myapp\models.py", line 1, in <module> from django.db import models ModuleNotFoundError: No module named 'django' Django is installed I only have python 3 I am not using a virtual env Is there a fix to this problem? Thank you -
SMTP AUTH extension not supported by server - Outlook SMTP & smtplib
I am trying to get emails sent from my django server using Outlook SMTP but I am getting this error: SMTPNotSupportedError( smtplib.SMTPNotSupportedError: SMTP AUTH extension not supported by server. I have tried: Set up 2FA on outlook and created app password for django to use, same error. Here is my configuration in settings: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.office365.com' EMAIL_PORT = 587 EMAIL_USE_STARTTLS = True EMAIL_HOST_USER = {removed} EMAIL_HOST_PASSWORD = {removed} Here is the view sending the email: def password_reset(request): if request.method == "POST": body_unicode = request.body.decode('utf-8') body_data = json.loads(body_unicode) email = body_data['email'] try: user = User.objects.get(email=email) token = default_token_generator.make_token(user) subject = 'x: Password Reset' body = f'Here is the link you requested to reset your password: http://localhost:3000/api/user/reset/{token}' sender = os.environ.get('EMAIL_NAME') recipient_list = [email] send_mail(subject, body, sender, recipient_list) return HttpResponse("Email sent") except User.DoesNotExist: return HttpResponse("User does not exist") else: return HttpResponse("Invalid HTTP method") Can anyone point me in the right direction? Thanks in advance! -
Django what is the logic behind creating in-app users the same way as admin users?
I was looking into how to create in-app users in Django by leveraging their auth system, and I founds this part of their docs: https://docs.djangoproject.com/en/dev/topics/auth/customizing/#extending-the-existing-user-model Personally, I do not like this approach because of three reasons: an in-app user will still have an empty permissions field. This is a bit scary, what if I misconfigure something? That could enable access to an in-app user to the admin panel. while both in-app user and admin panel users are similar in some aspects, they belong in two different worlds. To me, it would make more sense to have the auth system more flexible, and be able to use it with any kind of model, keeping the admin users separate from in-app users. having a separate model just to add more fields is an unnecessary overhead. But then, I am sure there are also some good reasons for this approach or maybe I am wrong and this is not the actual recommended approach. Any views on this? -
Why is my blacklisted token still allowing me to access an API in Django Rest Framework with Simple JWT?
In logout I blacklisted a token. But i can access a api using that blacklisted token. I used django restframework simple jwt and blacklist app for blacklisted token. In settings.py i have my jwt settings like this: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ] } SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': datetime.timedelta(minutes=60), 'REFRESH_TOKEN_LIFETIME': datetime.timedelta(days=1), 'USER_ID_CLAIM': 'id', 'ROTATE_REFRESH_TOKENS': True, 'BLACKLIST_AFTER_ROTATION': True, 'TOKEN_BACKEND': 'rest_framework_simplejwt.token_blacklist.backends.BlacklistBackend', 'BLACKLIST_TOKEN_CHECKS': [ 'rest_framework_simplejwt.token_blacklist.check_blacklisted_token', ], } In my views.py I am sharing two apis logout and hello api: from rest_framework.permissions import IsAuthenticated from rest_framework_simplejwt.authentication import JWTAuthentication from rest_framework import status from rest_framework.views import APIView from rest_framework.response import Response from rest_framework_simplejwt.tokens import RefreshToken class LogoutAPIView(APIView): def post(self, request): # Retrieve the user's refresh token from the request or any other means refresh_token = request.data.get('refresh') if refresh_token: try: print(refresh_token) token = RefreshToken(refresh_token) token.blacklist() # Blacklist the refresh token return Response({'detail': 'Successfully logged out.'}, status=status.HTTP_200_OK) except Exception as e: return Response({'detail': 'Invalid refresh token.'}, status=status.HTTP_400_BAD_REQUEST) else: return Response({'detail': 'Refresh token not provided.'}, status=status.HTTP_400_BAD_REQUEST) class HelloView(APIView): authentication_classes = [JWTAuthentication] permission_classes = [IsAuthenticated] def get(self, request): user = self.request.user return Response(f"Hello, {user.username}!") When ever i hit the hello api with a token which is blacklisted and stored in DB, the api stills sends me the content. -
django can you filter for different value for each object in one query
how to filter for different value for each object and is there is a better way to validate that amount of sales items wont be bigger than purchases items here is what I think is wrong in SaleItemListSerializer I am making a for loop and for each item I get its medicine and expiry date then finding sum by making 2 subquery and a query so if I have 15 item there will be 15 query on the database the total response time is in average about 0.8 s in sqlite but in mysql it grows to 1.5 ( still i want to add retrived items and disposed items in the supquery so it will grow bigger ) so is there is a way to annotate all medicine that are in items each with its expiry date ( which is stored in sale items and purchase items ) in one database query ? I think I am making alot of mistakes I am still new to django any help will be appreciated class SaleAddSerializer(serializers.ModelSerializer): items = serializers.ListField(child=serializers.DictField(),write_only=True,min_length=1) class Meta: model = Sale fields = ['doctor_name','coustomer_name','items'] def validate_items(self,items): seen_items = {} for item in items: if set(item.keys()) != {'medicine', 'quantity', 'price', … -
How to check if a field can be left blank in Django templates?
I have simple ModelForm. Some of those fields can be left blank. In the template I'd like to let the user know which fields are required (not to be left blank) and which are not required (can be left blank). How to do that? This did not work: {% for field in form.visible_fields %} {% if field.blank %} * {% endif %} {% endfor %} -
Django Google Authentication - Login page unformatted
I have a web page built using Django and I just followed a tutorial (https://www.section.io/engineering-education/django-google-oauth/) to add Google Authentication for user registration. The functionality works fine, I added a button that users can click and go to the Google Sign-in Page. However, this page is completely unformatted, and doesn't look like what's in the tutorial (the Google choose your account page that we've probably all seen). I can't for the life of me figure out why my site isn't serving the same formatted page. I have 2 urls.py files, one in my main app page, and one in a users folder. users/urls.py looks like this: from django.contrib import admin from django.urls import path, include from users import views as user_views from django.contrib.auth.views import LogoutView urlpatterns = [ path('register/', user_views.register, name='register'), path('login/', user_views.login_user, name='user-login'), path('accounts/', include('allauth.urls')), path('logout', LogoutView.as_view()), ] In my settings.py file, I've added SOCIALACCOUNT_PROVIDERS , SITE_ID and LOGIN_REDIRECT_URL . What else could I be missing that would affect the format of this page? -
Page not found | Can't serve media files with Django
That's the bit of code that causes the problem: <video width="320" height="240" controls> <source src="{{ movie_path }}" type="video/mp4"> </video> The error message: Using the URLconf defined in fergana_api.urls, Django tried these URL patterns, in this order: admin/ api/schema/ [name='api-schema'] api/docs/ [name='api-docs'] api/ [name='all-runs'] tests/<slug:test_session_id> [name='single-run'] tests/<slug:test_session_id>/<slug:test_name> [name='single-test'] ^files/(?P<path>.*)$ ^static/(?P<path>.*)$ The current path, vol/web/media/36/movies/movie.mt4, didn’t match any of these. I'm trying to serve a mp4 file from a volume that's outside the project. I thought I could render the page by providing the absolute path to the file, since it's how I'd do it if I tried to open that page as an html file in browser. But this just doesn't seem to work out though I see that 'The current path' looks exactly as it should look. Not sure it's required in this case, but it's my urls.py for the app urlpatterns = [ path('', views.AllRunsView.as_view(), name='all-runs'), path('tests/<slug:test_session_id>', views.SingleRunView.as_view(), name='single-run'), path('tests/<slug:test_session_id>/<slug:test_name>', views.SingleTestView.as_view(), name='single-test'), ] views.py class SingleTestView(View): def get(self, request, test_session_id, test_name): run = Runner.objects.get(id=test_session_id) movies_dir_path = to_file(run.artifacts_dir_path, 'movies') movie_path = to_file(movies_dir_path, test_name.replace('-', '_') + '.mp4') context = { 'movie_path': movie_path } return render(request, "presenter/single_test.html", context) settings.py # under what url to serve static files in prod STATIC_URL = '/static/' … -
Removing Queryset <>tags from being displayed with my query
I am trying to display a query to a template and I am getting the correct data output but it is being displayed with Queryset<>tags, I believe the reason for this is using .all within my template to make the query but I am unable to figure out how I would display the information with out using .all models.py class SectionMeetingDate(models.Model): section_date = models.DateField() # time stamps when a cost center is created or updated updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.section_date) class SectionMeeting(models.Model): user = models.CharField(max_length=200) section_meeting_date = models.ManyToManyField(SectionMeetingDate, related_name='section_meeting_date') # time stamps when a cost center is created or updated updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.user) class CostCenterID(models.Model): name = models.CharField(max_length=200) dept_leader = models.CharField(max_length=200, null=True, blank=True) section_leader = models.ManyToManyField(SectionMeeting, related_name='section_leader') department_meeting = models.ManyToManyField(DepartmentMeeting, related_name='section_leader') # time stamps when a cost center is created or updated updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name views.py def cost_center_id(request, pk): # provides the name of the section leaders for each cost center ID names = CostCenterID.objects.get(id=pk) context = { 'names':names, } return render(request, 'DeptSummary/cost_center_id.html', context) cost_center_id.html {% for section_leaders in names.section_leader.all %} <h5> Section Leader -- <a href="{% url 'section_leader_date' section_leaders.id %}"> …