Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python Django API authentication
I am new to Django. I need to use some API to get the .json format data. But the API needs authentication. I have already got the username and password. I see my colleague use Postman to enter the account then he can see the JSON file in intellij. I am in Pycharm, I am wondering is there some code I can use to realize the same function of postman rather than install the postman? What I have: API URL, account username and password Any help is really appreciated, also please let me know which file I should write in the Django, views.py?? Update: thank you for all the help!I am sorry I am not familiar with the postman, I only know my colleague show me how to enter the username and password. I have the API/URL, when I click on it, it will direct me to a page with JSON format data, looks like this {"businessOutcomes":[{"businessOutcomeId":"1234","origin":"JIRA",.....]} I have over 100 this kind of URL/API, I want to get the .json file in pycharm and so I can make them as the df to do the data analysis I want. And my colleague told me that the API has some … -
Cant run gTTS in Django
I am trying to build text to voice app and I had a problem with gTTS. the code I try views.py from django.shortcuts import render from gtts import gTTS from django import forms textfortts = [] class UploadFileForm(forms.Form): tts = forms.CharField(label= " convert text to audio here") def text_to_voice(request): if request.method == "POST" : form = UploadFileForm(request.POST) if form.is_valid(): tts = form.cleaned_data["tts"] textfortts.append(tts) obj = say(language='en-us', text= textfortts) return render(request, "text_to_voice_main.html",{ "form": UploadFileForm(), "lang": "en-us", "text": "text to say", }) text_to_voice_main.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Text to voice</title> </head> <body> <form action=""> {% csrf_token %} <audio src="{% say lang text %}" controls {% load gTTS %} ></audio> {{form}} <input type="submit"> </form> </body> </html> I need to have a text to voice converter. can i know what is the probelms and how i can fix it? -
Django forms passing request via get_form_kwargs fails to give form access to self.request.user
Goal I need to make the user accessible to a form for validation (i.e., through self.request.user) Approach Taken I use the get_form_kwargs() function in my view to make the request available to my form (as suggested here: Very similar problem). Problem Despite following the steps outlined in the StackOverflow answer linked above, I'm getting the error 'NoneType' object has no attribute 'user' Code views.py views.py class MemberDetailView(LoginRequiredMixin, generic.DetailView): """View class for member profile page""" model = User context_object_name = 'user' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs,) context['form'] = JoinCommunityForm() return context class JoinCommunityFormView(FormView): """View class for join code for users to join communities""" form_class = JoinCommunityForm def get_form_kwargs(self, *args, **kwargs): form_kwargs = super().get_form_kwargs(*args, **kwargs) form_kwargs['request'] = self.request return form_kwargs def post(self, request, *args, **kwargs): """posts the request to join community only if user is logged in""" if not request.user.is_authenticated: return HttpResponseForbidden return super().post(request, *args, **kwargs) class MemberDashboardView(View): """View class to bring together the MemberDetailView and the JoinCommunityFormView""" def get(self, request, *args, **kwargs): view = MemberDetailView.as_view() return view(request, *args, **kwargs) def post(self, request, *args, **kwargs): view = JoinCommunityFormView.as_view() form = JoinCommunityForm(request.POST) if form.is_valid(): forms.py forms.py from communities.models import Community, UserRoleWithinCommunity class JoinCommunityForm(forms.Form): pin = forms.RegexField('^[A-HJ-NP-Z1-9]$', max_length=6, label='', widget=forms.TextInput(attrs={'oninput': 'this.value = this.value.toUpperCase()'})) … -
Getting error : django.db.utils.IntegrityError: UNIQUE constraint failed: auth_user.username || I'm a beginner trying to save in Djnago
I'm trying to learn django. Just started with a project. It has 2 applications so far. Employee poll I'm trying to do it via CMD. It shows the following issues. Actually I was trying to follow a tutorial for a django project. I checked, there is no UNIQUE keyword used in the code. I even tried deleting and then saving but didn't resolve. Employee :-- **models.py (employee) : ** from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) designation = models.CharField(max_length=20, null=False, blank=False) salary = models.IntegerField(null=True,blank=True) class Meta: ordering = ('-salary',) #minus sign indicates that we need the result in decending order def __str__(self): return "{0} {1}". format(self.user.first_name, self.user.last_name) @receiver(post_save, sender=User) def user_is_created(sender, instance, created, **kwargs): if created: Profile.object.create (user=instance.) else: instance.profile.save() Poll :-- **models.py (poll)** from django.db import models from django.contrib.auth.models import User # Create your models here.` `class Question(models.Model): # models.Model is the base model. we just need to extend it. #All the class varibales will be considered as the columns of the table. title = models.TextField(null=True, blank = True) status = models.CharField(default = 'inactive', max_length=10) #if we don't pass … -
use django-filters on a queryset in the backend
Assuming I have a queryset and some filters I got from the front end, can I use the pre-defined FilterSet to filter over the queryset? example: models.py class User(models.Model): name = models.CharField(...) score = models.IntegerField(...) filters.py class UserFilter(django_filters.FilterSet): q = django_filters.CharFilter(method="text_search_filter") score_min = django_filters.NumberFilter(field_name="score", lookup_expr="gte") score_max = django_filters.NumberFilter(field_name="score", lookup_expr="lte") class Meta: model = User fields = {} def text_search_filter(self, queryset, name, value): return queryset.filter(name__icontains=value) views.py class UserView(View): filter_class = UserFilter ... def post(self, request, **kwargs): qs = User.object.all() filters = {"q": "john doe", "score_min": 5, "score_max": 10} Can I call UserFilter and pass the filter dict? To prevent me applying those filters again, since I already have those defined in the UserFilter Here's what I tried and didn't work: views.py def post(self, request, **kwargs): qs = User.object.all() filters = {"q": "john doe", "score_min": 5, "score_max": 10} filter = UserFilter(request.GET, queryset=qs) filter.is_valid() qs = filter.filter_queryset(qs) # Did not apply the filters -
Flutter Failed to detect image file format using the file header. Image source: encoded image bytes
I have a django server that has media served by nginx, I'm trying to load the media into my flutter app: Image.network( valueOrDefault<String>( FFAppState().user.photo, 'https://stpeterlibrary.crabdance.com/static/images/LOGO%201.png', ) The static images from the same site load just fine but the network images don't load at all, and give me this error: Failed to detect image file format using the file header. File header was [0x3c 0x21 0x44 0x4f 0x43 0x54 0x59 0x50 0x45 0x20]. Image source: encoded image bytes the static file at images/LOGO%201.png is shown before the page loads the photos, then if the photo is null it shows the same error even though it was working. I think the error is related to the widget that is loading the image Padding( padding: EdgeInsetsDirectional.fromSTEB(16.0, 16.0, 16.0, 16.0), child: InkWell( splashColor: Colors.transparent, focusColor: Colors.transparent, hoverColor: Colors.transparent, highlightColor: Colors.transparent, onTap: () async { await Navigator.push( context, PageTransition( type: PageTransitionType.fade, child: FlutterFlowExpandedImageView( image: Image.network( valueOrDefault<String>( FFAppState().user.photo, 'https://stpeterlibrary.crabdance.com/static/images/LOGO%201.png', ), fit: BoxFit.contain, ), allowRotation: false, tag: valueOrDefault<String>( FFAppState().user.photo, 'https://stpeterlibrary.crabdance.com/static/images/LOGO%201.png', ), useHeroAnimation: true, ), ), ); }, child: Hero( tag: valueOrDefault<String>( FFAppState().user.photo, 'https://stpeterlibrary.crabdance.com/static/images/LOGO%201.png', ), transitionOnUserGestures: true, child: ClipRRect( borderRadius: BorderRadius.circular(12.0), child: Image.network( valueOrDefault<String>( FFAppState().user.photo, 'https://stpeterlibrary.crabdance.com/static/images/LOGO%201.png', ), width: MediaQuery.of(context).size.width * 1.0, height: 230.0, fit: BoxFit.contain, ), ), ), … -
How to connect my EXPO GO app in IOS to my django server? (both running on wsl)
I'm doing a project using React Native/EXPO and Django. It's not my first time using Django, but it's my first time working on mobile development. I have both of my repositories in WSL, but I can't find a way to consume an API from Django Server when I run the app on my Iphone (after reading the QR Code). I always get the same error:[AxiosError: timeout exceeded]. But if I try to consume this API with the WSL ip in postman, it works perfectly. I know that it's an IP/Port problem, but I don't know how to solve it. I would really appreciate some help here. Django Server Settings.py ALLOWED_HOSTS = ["*"] CORS_ALLOW_ALL_ORIGINS = True React-native code login.tsx const handleLogin = async () => { const networkState = await Network.getNetworkStateAsync(); console.log(networkState); const ipAddress = await Network.getIpAddressAsync(); console.log('Endereço IP:', ipAddress); try { const response = await axios.post('http://172.29.160.117:8000/api/token/', { email: email, password: password, }); const accessToken = response.data.access; // Salve o token de acesso no aplicativo (por exemplo, no AsyncStorage) console.log("Resposta do servidor: " + accessToken); // navigation.navigate('ScreenHome'); } catch (error) { console.log(error); } console.log("Finalizou função"); }; Terminal Output -
while implementing django-defender, Error (if response.get("X-Frame-Options") is not None: AttributeError: 'function' object has no attribute 'get')
Implementing a django-defender in web application causing an error while adding a syntax @watch_login in views.py /views.py from defender.decorators import watch_login ...`` @watch_login # error caused due to... def login_user(request): ... return render(request, 'login.html') Error- Internal Server Error: /login Traceback (most recent call last): File "/.local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/.local/lib/python3.8/site-packages/django/utils/deprecation.py", line 136, in __call__ response = self.process_response(request, response) File "/.local/lib/python3.8/site-packages/django/middleware/clickjacking.py", line 27, in process_response if response.get("X-Frame-Options") is not None: AttributeError: 'function' object has no attribute 'get' [28/Jun/2023 11:40:18] "GET /login HTTP/1.1" 500 62726 Any solution for it... ThankYou -
xhtml2pdf keep-with-previous.within-page
I'm using the xhtml2pdf library in Django 3.x. I don't know how to make the style work in the template, and still transfer text that is too long to the next page, but only its further part. I'm currently using this code snippet, the rest of the text is moved to the next page, but the styles don't work: <xsl:attribute name="keep-with-previous.within-page"> <tr> <th class="col332"> {{ instance.myvar|linebreaks }} </th> </tr> </xsl:attribute> -
Please I don't understand why my code keeps misbehaving [closed]
The profileimg attribute doesn't seem to work right. class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) id_user = models.IntegerField() bio = models.TextField(blank=True) profileimg = models.ImageField(upload_to='profile_images', default='media/default_img.png') location = models.CharField(max_length=100, blank=True) I've tried using an IF block <div class="col-span-2"> <label for="profile">Profile Image</label> {% if user_profile.profileimg %} <img src="{{ user_profile.profileimg.url }}" width="100" height="100" alt="profile image" /> {% endif %} <input type="file" name="profile_img" class="shadow-none bg-gray-100"> </div> -
Imagine dont display in html page (Django) [closed]
In html file <img src="{% static 'images/welcome-left.png' %}"> this in settings.py STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, '/static/') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATICFILES_DIRS = [ os.path.join(BASE_DIR, "todoapp/static/"), ] maybe error in paths -
Cannot debug app views in DJANGO project using VSCode
I have created an application using the DJANGO framework to create several API programs. To do this I created an app that is now in the installed list of apps. I can debug the manage.py file as the server starts up. But I cannot debug subsequent calls to views in apps, the views.py breakpoints are never hit? However, this is never reached This is what my launch JSON looks like: { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Python: Django", "type": "python", "request": "launch", "program": "${workspaceFolder}\\manage.py", "args": [ "runserver", "--noreload" ], "env": { "DJANGO_SETTINGS_MODULE": "django-sql-project.settings" }, "django": true, "justMyCode": true } ] } and my VS Settings json looks like this: { "python.defaultInterpreterPath":"~//env//Scripts//python.exe", "python.terminal.activateEnvironment": true, "appService.zipIgnorePattern": [ "__pycache__{,/**}", "*.py[cod]", "*$py.class", ".Python{,/**}", "build{,/**}", "develop-eggs{,/**}", "dist{,/**}", "downloads{,/**}", "eggs{,/**}", ".eggs{,/**}", "lib{,/**}", "lib64{,/**}", "parts{,/**}", "sdist{,/**}", "var{,/**}", "wheels{,/**}", "share/python-wheels{,/**}", "*.egg-info{,/**}", ".installed.cfg", "*.egg", "MANIFEST", ".env{,/**}", ".venv{,/**}", "env{,/**}", "venv{,/**}", "ENV{,/**}", "env.bak{,/**}", "venv.bak{,/**}", ".vscode{,/**}" ] } -
How to handle scaling down ECS containers when a Celery worker completes a task?
How can I handle scale-down policies properly when using SQS as a broker and celery with celery beat for task scheduling in a Django app? I have successfully created a scale-up policy that adds new containers when there is a new message in SQS. However, I am facing challenges in implementing a scale-down autoscaling policy. When I choose the "NumberOfMessagesSent" metric for scale-down, it removes tasks before the worker finishes their job. This becomes problematic especially with long-running tasks that can last for several hours. My goal is to ensure that if a celery task's status is "STARTED," the worker responsible for executing the task should be kept alive until the status changes to "SUCCESS" or "FAILURE." How can I achieve this? -
How to group by AND annotate MODELS with django
I have this: class City(models.Model): postal_code = models.IntegerField() class CountryViewset(GenericViewSet, ListModelMixin, RetrieveModelMixin): queryset = City.objects.values("country_code").annotate(cities_ids=ArrayAgg("id")) serializer_class = CountrySerializer class CountrySerializer(serializers.Serializer): country_code = serializers.IntegerField() cities_ids = serializers.ListField(child=serializers.IntegerField()) I got: { country_code: 1, cities_ids: [1, 2, 3], } Is it possible to annotate objects directly ? I want my Country queryset to look like this: <Queryset [ { country_code: 1, cities_ids: <QuerySet [<City: 1>, <City: 2>, <City: 3>]>, }, ... ]> Because for the future I will add a lot of django filters and I don't want to get/filter City objects everytime I do operations for performance purposes. I cannot create Country Model because I'm not allowed to use manage command to sync regularly Country models. -
How to setup redis service with django
I am creating a django CI pipeline using github actions but I am getting the following error. Found 23 test(s). System check identified no issues (0 silenced). EEEEEEEEEEEEs.......... ====================================================================== ERROR: test_account_str (blog.tests.test_models.TestAccount) ---------------------------------------------------------------------- Traceback (most recent call last): File "/opt/hostedtoolcache/Python/3.9.17/x64/lib/python3.9/site-packages/redis/connection.py", line 699, in connect sock = self.retry.call_with_retry( File "/opt/hostedtoolcache/Python/3.9.17/x64/lib/python3.9/site-packages/redis/retry.py", line 46, in call_with_retry return do() File "/opt/hostedtoolcache/Python/3.9.17/x64/lib/python3.9/site-packages/redis/connection.py", line 700, in <lambda> lambda: self._connect(), lambda error: self.disconnect(error) File "/opt/hostedtoolcache/Python/3.9.17/x64/lib/python3.9/site-packages/redis/connection.py", line 970, in _connect for res in socket.getaddrinfo( File "/opt/hostedtoolcache/Python/3.9.17/x64/lib/python3.9/socket.py", line 954, in getaddrinfo for res in _socket.getaddrinfo(host, port, family, type, proto, flags): socket.gaierror: [Errno -3] Temporary failure in name resolution My github actions workflow file looks like this services: redis_db: image: redis # env: # CELERY_BROKER_URL: ${{env.CELERY_BROKER_URL}} # CELERY_RESULT_BACKEND: ${{env.CELERY_RESULT_BACKEND}} # REDIS_HOST: localhost # REDIS_PORT: 6379 # ports: # - 6379:6379 options: >- --health-cmd "redis-cli ping" --health-interval 10s --health-timeout 5s --health-retries 5 Kindly assist me in identifying the issue. I tried to run the job in a container and directly in the runner but the error still persists -
Change django createAt field
I have this model: class Temp(models.Model): user = models.ForeignKey(to=User, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) sometimes I want to create an object of this class with a fixed time, but it ignores time and sets times with auto_now_add: data = {'created_at': datetime.datetime.now()} temp = TempSerializer(data=data) what can I do? -
Bug after Stripe payment
I have a website with games. I also included stripe as a payment method, and everything works pretty fine! But, after you finish your payment, you get redirected to your home page, and objects that are looped just DISSAPPEAR! They appear again once you travel from one page to another. Is this a bug in STRIPE or is this something to do with my code? -
Exception Type: NoReverseMatch Exception Value: 'orders' is not a registered namespace
I'm newbie in django and now I'm studiyng by book from Antonio Mele "Django_3_By_Example_Build_powerful_and_reliable_Python_web_applications" I have a question: When I try to pass into cart_detail from the item description page I receive a mistake: Exception Value: 'orders' is not a registered namespace full track below: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/cart/ Django Version: 3.0.14 Python Version: 3.11.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django_extensions', 'django.contrib.contenttypes', 'django.contrib.sessions', 'cart.apps.CartConfig', 'django.contrib.messages', 'django.contrib.staticfiles', 'shop.apps.ShopConfig'\] Installed Middleware: 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'\] Template error: In template C:\\Python\\django-sites\\myshop\\myshop\\shop\\templates\\shop\\base.html, error at line 0 'orders' is not a registered namespace 1 : {% load static %} 2 : \<!DOCTYPE html\> 3 : \<html\> 4 : \<head\> 5 : \<meta charset="utf-8" /\> 6 : \<title\>{% block title %}My shop{% endblock %}\</title\> 7 : \<link href="{% static "css/base.css" %}" rel="stylesheet"\> 8 : \</head\> 9 : \<body\> 10 : \<div id="header"\> Traceback (most recent call last): File "C:\\Python\\django-sites\\myshop\\venv\\Lib\\site-packages\\django\\urls\\base.py", line 72, in reverse extra, resolver = resolver.namespace_dict\[ns\] During handling of the above exception ('orders'), another exception occurred: File "C:\\Python\\django-sites\\myshop\\venv\\Lib\\site-packages\\django\\core\\handlers\\exception.py", line 34, in inner response = get_response(request) File "C:\\Python\\django-sites\\myshop\\venv\\Lib\\site-packages\\django\\core\\handlers\\base.py", line 115, in \_get_response response = self.process_exception_by_middleware(e, request) File "C:\\Python\\django-sites\\myshop\\venv\\Lib\\site-packages\\django\\core\\handlers\\base.py", line 113, in \_get_response response = wrapped_callback(request, \*callback_args, \*\*callback_kwargs) File "C:\\Python\\django-sites\\myshop\\myshop\\cart\\views.py", line 34, … -
Django user update
I want to update User's data, but instead of overwriting the data, it tries to register a new user. How do I make it work? The class looks like this: class SignUpForm(UserCreationForm): email = forms.EmailField(label="", widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Email Address'})) first_name = forms.CharField(label="", max_length=100, widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'First Name'})) last_name = forms.CharField(label="", max_length=100, widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Last Name'})) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2') def __init__(self, *args, **kwargs): super(SignUpForm, self).__init__(*args, **kwargs) self.fields['username'].widget.attrs['class'] = 'form-control' self.fields['username'].widget.attrs['placeholder'] = 'User Name' self.fields['username'].label = '' self.fields['username'].help_text = '<span class="form-text text-muted"><small>Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.</small></span>' self.fields['password1'].widget.attrs['class'] = 'form-control' self.fields['password1'].widget.attrs['placeholder'] = 'Password' self.fields['password1'].label = '' self.fields['password1'].help_text = '<ul class="form-text text-muted small"><li>Your password can\'t be too similar to your other personal information.</li><li>Your password must contain at least 8 characters.</li><li>Your password can\'t be a commonly used password.</li><li>Your password can\'t be entirely numeric.</li></ul>' self.fields['password2'].widget.attrs['class'] = 'form-control' self.fields['password2'].widget.attrs['placeholder'] = 'Confirm Password' self.fields['password2'].label = '' self.fields['password2'].help_text = '<span class="form-text text-muted"><small>Enter the same password as before, for verification.</small></span>' And the views.py part like this: def update_user(request): if request.user.is_authenticated: current_user = User.objects.get(id=request.user.id) profile_user = Profile.objects.get(user__id=request.user.id) # Get Forms user_form = SignUpForm(request.POST or None, request.FILES or None, instance=current_user) profile_form = ProfilePicForm(request.POST or None, request.FILES or None, instance=profile_user) if … -
How to link to a parametrized urlpattern?
I have a parametrized urlpattern path("editpage/<str:title>", views.editpage, name="editpage") How would i go about and provide a link to this in the html? <a href="/editpage/{{ title }}">{{ title }}</a> I dont want something like this, where the link is "hardcoded". Rather i want to use the feature '{% url 'editpage' %}'. But this yields: Reverse for 'editpage' with no arguments not found. But how do i pass in the extra information? I tried '{% url 'editpage' title='{{ title }}' %}', but that doesnt work -
New django dashboard for free
I started a project on kickstarter in which I'm making a dashboard for managing a server in django. I do it in react and django. The panel will be available for free after release. Please support me :) (I know that it's not question) KICKSTARTER -
Troubleshooting Increasing Memory Usage in a Django Application Deployed on AWS
We've successfully built a web application employing React for the frontend and Django, coupled with the Django Rest Framework (DRF), for the backend. The backend component has been deployed on Amazon Web Services (AWS) via the EC2 and ECS services. Currently, I'm observing a steady rise in memory usage for my container, as evidenced by the below graph. The dips you see in the graph correspond to application deployments. For managing our HTTP server, we're utilizing Gunicorn. The command used as an entry point is as follows: gunicorn booking_system.wsgi:application --bind 0.0.0.0:8000 --workers=$workers --max-requests 100 --max-requests-jitter 25 This command is intended to avert memory leaks by restarting the Gunicorn worker after a certain number of requests. I would appreciate any advice you can offer. What diagnostic measures can I take to discern the reason behind the escalating memory usage? Adding these options --workers=$workers --max-requests 100 --max-requests-jitter 25 I would expect to maintain a regular memory consumption. -
Django template cannot be found
I'm trying to render a template using django but keep getting an error saying that the template could not be found even though I have made a template folder with the html file in it. I am following this tutorial. This is the error I get: Internal Server Error: /playground/hello/ Traceback (most recent call last): File "/Users/shavakvasania/.local/share/virtualenvs/compia-kMxYXwId/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/Users/shavakvasania/.local/share/virtualenvs/compia-kMxYXwId/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/shavakvasania/Desktop/compia/playground/views.py", line 5, in say_hello return render(request, 'hello.html') File "/Users/shavakvasania/.local/share/virtualenvs/compia-kMxYXwId/lib/python3.10/site-packages/django/shortcuts.py", line 24, in render content = loader.render_to_string(template_name, context, request, using=using) File "/Users/shavakvasania/.local/share/virtualenvs/compia-kMxYXwId/lib/python3.10/site-packages/django/template/loader.py", line 61, in render_to_string template = get_template(template_name, using=using) File "/Users/shavakvasania/.local/share/virtualenvs/compia-kMxYXwId/lib/python3.10/site-packages/django/template/loader.py", line 19, in get_template raise TemplateDoesNotExist(template_name, chain=chain) django.template.exceptions.TemplateDoesNotExist: hello.html the issue is likely just that the interpreter can't find the correct templates folder but not sure how to fix. I added the application to settings.py.(https://i.stack.imgur.com/cv6XO.png) Created all the urls in the main urls and in the playground app urls. Here are my template settings in case something is wrong there but I just followed what the tutorial said to do: -
compatibility between django version of 1.11.23 and postgres version of 13.8
My application uses django version of 1.11.23. I am thinking of switching the postgres version to 13.8, currently I m using 12.7 of postgres version. May I know if anyone faced compatibility issues while connecting django version 1.11.23 to 13.8 version of postgres -
Filtering from a pivot table on Django Rest Framework returns all the values
I have a project in Django using Django Rest Framework with this models. job.py from django.db import models from .base import BaseModel class Job(BaseModel): title = models.CharField(max_length=100) races = models.ManyToManyField('Race', through='JobRace') skills = models.ManyToManyField('Skill') def __str__(self): return f"{self.title}" race.py from django.db import models from .base import BaseModel class Race(BaseModel): name = models.CharField(max_length=100) ... image = models.ImageField(default=None) description= models.TextField(blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return f"{self.name} and jobRace.py who is the pivot table between jobs a races, I specified instead of letting Django auto generate it because I wanted to add an aditional image field to the pivot table from django.db import models from rpg.models.job import Job from rpg.models.race import Race from .base import BaseModel class JobRace(BaseModel): job = models.ForeignKey(Job, related_name='job_race', on_delete=models.CASCADE) race = models.ForeignKey(Race, related_name='job_race', on_delete=models.CASCADE) image = models.ImageField(null=True, blank=True, upload_to='jobs/') def __str__(self): return f"{self.job.title} - {self.race.name}" with their serializers job.py from rest_framework import serializers from ..models.job import Job from .skill import SkillSerializer from .jobRace import JobRaceSerializer class JobSerializer(serializers.ModelSerializer): job_race = JobRaceSerializer(many=True,read_only=True) class Meta: model = Job fields = '__all__' race.py from rest_framework import serializers from ..models.race import Race class RaceSerializer(serializers.ModelSerializer): class Meta: model = Race fields = '__all__' jobRace.py from rest_framework import serializers from ..models.jobRace import …