Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Wagtail - Heroku: How to troubleshoot intermittent, seemingly random, HTTP 404s?
I'm serving Wagtail pages in a very well tested web app. No errors show up in development. When in Production (using Heroku and a hobby-tier Postgres db), those pages occasionally return an HTTP 404. If I refresh the browser a couple times, it goes back to serving the Page perfectly again. Some details: This happens with multiple pages; I get emails with the 404 error when this happens, so Django's BrokenLinkEmailsMiddleware is kicking in; Heroku web Dyno looks healthy based on its metrics; Heroku Postgres has no logs for the Hobby tier, so I don't know what's going on on the db side; Server is running behind a Cloudflare proxy server, but I can see the request hitting the origin and returning a 404. I'm obviously not expecting a solution here since the above info is insufficent for that. But I'm looking for troubleshooting pointers, for example: If the db has become under-dimensioned (too little RAM, too many simultaneous connections, etc.) - could that result in a Wagtail db query wrongly returning PageNotFound? Or would that return a 500 Server Error? How can I test DB error-handling locally with Django? How can I add a full Traceback for the Django … -
how to authenticate Angular and Django Rest Framework
I need to build an application where only logged in users can access a type of information using Angular in Front and Django Rest Framework in back. I just can't do this authentication, I tried and researched in every way, even using simple-jwt, I can't succeed. If anyone has been working on this, could you please help me or suggest me a site with a complete example. Here is my code bellow: settings.py # ALLOWED_HOSTS=['*'] # CORS_ORIGIN_ALLOW_ALL = True ALLOWED_HOSTS=['localhost', '127.0.0.1'] CORS_ORIGIN_ALLOW_ALL = False CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_WHITELIST = ( 'http://localhost:4200', ) # JWT settings SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'AUTH_HEADER_TYPES': ('Bearer',), } accounts/views.py class UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = MyUser.objects.all() serializer_class = UserSerializer # renderer_classes = (UserJSONRenderer,) permission_classes = [permissions.IsAuthenticated] account/urls.py # app_name = 'accounts' router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) router.register(r'groups', views.GroupViewSet) # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ path('', include(router.urls)), path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), ] And from my Angular auth.service.ts import { HttpClient, HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpHeaders } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { … -
why are only some css classes being generated in tailwind and others aren't?
I have a project where I'm using Django as backend and tailwind for the css. tailwind is not giving me any errors and is finding classes in my files but not generating the css. the only class that its working for is bg-blue-500 and nothing else. if anyone could think of why this may be happening or how to fix is I would really appreciate it. html page <ul class="nav"> <li class= "bg-red-500"> <a class="" href="{% url 'activeListings' %}">Active Listings</a> </li> {% if user.is_authenticated %} <li class=" bg-blue-500"> <a class="" href="{% url 'logout' %}">Log Out</a> </li> {% else %} <li class=""> <a class="" href="{% url 'login' %}">Log In</a> </li> <li class=""> <a class="" href="{% url 'register' %}">Register</a> </li> tailwind.css @tailwind base; @tailwind components; @tailwind utilities; @layer base { h1 { @apply text-4xl; } h2 { @apply text-3xl; } h3 { @apply text-2xl; } h4 { @apply text-xl; } } package.json { "name": "jstools", "version": "1.0.0", "description": "", "main": "tailwind.config.js", "scripts": { "build": "tailwind build -i ../auctions/tailwind.css -o ../auctions/output.css && cleancss -o ../auctions/output.min.css ../auctions/output.css" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "autoprefixer": "^10.4.12", "clean-css-cli": "^5.6.1", "tailwindcss": "^3.1.8" } } tailwind.config /** @type {import('tailwindcss').Config} */ module.exports = { future: { … -
django class view access response
in function view: def view(request): # do something with request response = render(request, 'view.html') # do something with response return response but now I have a View class: class ArticleDeleteView(View): pass # or even something more complicated class ArticleDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): pass which function shall I overwrite to access to the response? -
How i can cache SerializerMethodField result
I have a serializer: class OrderItemResponseSerializer(serializers.ModelSerializer): prepack_qty = serializers.SerializerMethodField() product_description = serializers.SerializerMethodField() class Meta: model = OrderItem fields = ( "product", "qty_ordered", "qty_approved", "status", "prepack_qty", "product_description" ) def get_prepack_qty(self, obj): return obj.product.prepack_quantity def get_product_description(self, obj): return obj.product.product_description When I make a get request to /orders, I make a lot of sql queries to the database because different orders may contain the same product. How i can cache result of get_prepack_qty and get_product_description methods? I tried to use @cached_property this way: class OrderItem(models.Model): ... @cached_property def item_product_description(self): return self.product.product_description but the number of requests to the database remained the same. -
Submitting a form from Vue component to POST data into django backend database
Where is the relationship between a form (found in a vue component) and a django backend meant to be defined? For my frontend, I am using VueJS, my main component is able to fetch data from json file using an api defined in my django view and url file. I do not understand how after filling in my Vue form, I may directly submit data to my django database. Tutorials online utlise django's built-in form related features; this, I am not after. -
Reverse for 'people' not found. 'people' is not a valid view function or pattern name
I got the error in my title when I tried to add a URL link so I can get to the person when I click on the URL. Beginner here so sorry if I am making silly mistakes. I am not sure where in my view function I messed up so any help is really appreciated views.py from django.shortcuts import render from django.views.generic.list import ListView from django.views.generic.detail import DetailView from .models import People # Create your views here. class pplList(ListView): model = People context_object_name = 'people' class pplDetail(DetailView): model = People context_object_name ='cnd' template_name = 'base/people.html' people_list.html <h1>Interviewee Dashboard</h1> <table> <tr> <th> Item</th> <th> </th> </tr> {% for cnd in people %} <tr> <td>{{cnd.name}}</td> <td><a href="{% url 'people' cnd.id %}">View</a></td> </tr> {% empty %} <h3>No items in list</h3> {% endfor %} </table> models.py from unittest.util import _MAX_LENGTH from django.db import models from django.contrib.auth.models import User # Create your models here. status_choices = ( ("Choose", "Choose"), ("Resume Submitted","Resume Submitted"), ("Resume Reviewed", "Resume Reviewed"), ("Interview Scheduled","Interview Scheduled" ), ("Interview Completed","Interview Completed" ), ) wl = ( ("Choose", "Choose"), ("Accepted", "Accepted"), ("Rejected", "Rejected"), ) class People(models.Model): # user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=200) age = models.IntegerField(null=True, blank=True) address = models.TextField(null=True, … -
Reporting data entries in the project
In the project I use Django and PostgreSql, there is data entry every day. I want to receive the data of that day at the time I set myself, convert it into pdf and send it as an e-mail. Is there something automatic to do this all the time or what kind of script or query should I write? In other words, I want to do a reporting process on a daily basis, but I want to ensure that it is done automatically. -
How to host a django project on a hostinger vps?
I have a django project. I want to host it on a vps. I saw a few vps services and liked the hostinger vps.I want to host it to that vps. But the problem is, I am using django celery.I am also using django channels(WebSocket). It means,you know, I'm using asgi. And I want to use apache server with it. Can I know how to deploy this project on a vps? -
Django REST: Authentication credentials were not provided
There are similar questions like this on StackOverflow which didn't solve my problem. I'm using Postman to test my APIs. For some reason, my token authorization is not working and it's showing the following message, "detail": "Authentication credentials were not provided." My settings.py: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', ], } These are my installed apps: ... 'rest_framework', 'rest_framework.authtoken', 'allauth', 'allauth.account', 'dj_rest_auth', 'dj_rest_auth.registration', ... I spent some hours to find the problem but failed. Can anyone please help me with where might the problem be? -
Context data not passing to Django templates
My cart view. I have passed context on return but it doesn't appear on the templates. If i print the def cart(request): total = 0 quantity = 0 cart_items = None tax = None grand_total = None try: cart = Cart.objects.get(cart_id=_cart_id(request)) cart_items = CartItem.objects.filter(cart=cart, is_active=True) for cart_item in cart_items: total += (cart_item.product.price * cart_item.quality) quantity = cart_item.quality tax = (total / 100) * 2 grand_total = total + tax except: pass context = { 'total': total, 'quantity': quantity, 'cart_items': cart_items, 'tax': tax, 'grand_total': grand_total, } return render(request, 'c.html', context) Html Template. Here I created a for loop to get items from the array. But It doesn't show any objects from the array. But always print "Item" string for each object. {% extends 'base.html' %} {% load static %} {% block content %} {% extends 'base.html' %} {% load static %} {% block content %} {% for item in cart_items %} item.product.product_name {% endfor %} {% endblock %} {% endblock %} -
Symmetric django model
I want to create a model, which is symmetric on two fields. Let's call the model Balance: class Balance (models.Model): payer = models.ForeignKey(auth.User, ...) payee = models.ForeignKey(auth.User, ...) amount = models.DecimalField(...) It should have the following property: balance_forward = Balance.objects.get(payer=USER_1, payee=USER_2) balance_backward = Balance.objects.get(payer=USER_2, payee=USER_1) balance_forward.amount == -1 * balance_backward.amount What is the best way to implement this? -
How to Filter out Django Models
How do I create a lesson in a course without it showing in another course. I have a foreign key which is the course and it is under the models Lesson. I want to only view the lesson that is created under the certain course. But my problem is when I create a lesson in course 1, the lesson also shows in course 2. (sorry for bad english) views.py from django.shortcuts import render, redirect from django.views.generic import ListView, DetailView from courses.forms import AddCourseForm, AddSectionForm, AddLessonForm from courses.models import Course, Section, Lesson def coursepage(request): courses = Course.objects.all() if request.user.is_authenticated: return render(request, "courses/courses.html", {'courses': courses}) else: return redirect('loginpage') def addcourse(request): if request.method == "POST": form = AddCourseForm(request.POST) if form.is_valid(): form.save() return render(request, "courses/successcourse.html", {'form1': form}) form = AddCourseForm() return render(request, "courses/addcourse.html", {'form': form}) def updatecourse(request, id): course = Course.objects.get(id=id) context = { 'course': course } return render(request, 'courses/editcoursehtml', context) def updatecourserecord(request, id): course = Course.objects.get(id=id) form = AddCourseForm(request.POST, instance=course) if form.is_valid(): form.save() return redirect("coursepage") return render(request, 'courses/editcourse.html', {'course':course}) def deletecourse(request, id): course = Course.objects.get(id=id) course.delete() return redirect("coursepage") class CourseDetailView(DetailView): queryset = Course.objects.all() template_name = "courses/detail.html" def sectionspage(request): section = Section.objects.all() if request.user.is_authenticated: return render(request, "sections/sections.html", {'sections': section}) else: return redirect('loginpage') def addsections(request): … -
not able to authenticate access_token comming from flutter app in django using google-oauth2 errors come up like your "credentials are not correct"
@api_view(['POST']) @permission_classes([AllowAny]) @psa() def register_by_access_token(request, backend): token = request.data.get('access_token') user = request.backend.do_auth(token) print(request) if user: token, _ = Token.objects.get_or_create(user=user) return Response( { 'token': token.key }, status=status.HTTP_200_OK, ) else: return Response( { 'errors': { 'token': 'Invalid token' } }, status=status.HTTP_400_BAD_REQUEST, ) so above is the code and this is the URL re_path('api/register-by-access-token/' + r'social/(?P<backend>[^/]+)/$', register_by_access_token), But all the time user = request.backend.do_auth(token) this thing is giving error that "credentials are not correct" -
How to retrieve random records of Django ORM on a weekly basis
I am new to Django and I'd need some help for a project I have. I am currently building the API using Django-Rest-Framework and I would like to have a view which returns a weekly list of exercises. I am not sure how i could make it so the queried objects change weekly... atm I've created a custom Manager which retrieves a random amount of exercises from the exercise db Models.py class ExerciseManager(models.Manager): random_exercises = [] def random(self, amount=20): self.random_exercises.clear() exercises = Exercise.objects.all() for i in range(amount): self.random_exercises.append(random.choice(exercises)) return self.random_exercises class Exercise(models.Model): name = models.CharField(max_length=100, unique=True) objects = ExerciseManager() def __str__(self): return f"{self.name}" views.py @api_view(['GET']) def exercise_list(request): exercises = Exercise.objects.random() serializer = ExerciseSerializer(exercises, many=True) return Response(serializer.data) -
I use django auth in my project. how can i overwrite login view to add a remember me view?
This is my urls.py: from django.urls import path, reverse_lazy from django.contrib.auth import views as auth_views from .forms import EmailValidationOnForgotPassword from . import views app_name = 'account' urlpatterns = [ path('', views.dashboard, name='dashboard'), path('login/', auth_views.LoginView.as_view(), name='login'), path('logout/', auth_views.LogoutView.as_view(), name='logout'), path('password_change/', auth_views.PasswordChangeView.as_view(success_url=reverse_lazy('account:password_change_done')), name='password_change'), path('password_change/done', auth_views.PasswordChangeDoneView.as_view(), name='password_change_done'), path('password_reset/', auth_views.PasswordResetView.as_view(form_class=EmailValidationOnForgotPassword, success_url=reverse_lazy('account:password_reset_done')), name='password_reset'), path('password_reset/done', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), path('reset/<uidb64>/<token>', auth_views.PasswordResetConfirmView.as_view(success_url=reverse_lazy('account:password_reset_complete')), name='password_reset_confirm'), path('reset/done', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete'), ] Is there any attributes i can use like 'success_url' or 'form_class' -
form is not submit and load another page in production
i have a form page which work perfectly in locally but after uploading it to railway it start showing this error I also checked locally it worked perfectly fine and load the page when click forms submit button but in production it throws above mentioned error here is my form template <form action="{% url 'personal_readme:preview' %}" method="POST" enctype="multipart/form-data"> **{% csrf_token %}** <div class="name_tag"> <h2><iconify-icon icon="bi:person-circle"></iconify-icon> ( Title )</h2> {{ form.name.label_tag }} <span>{{ form.name }}</span> </div> <hr> <div class="support_tag"> <h2><iconify-icon icon="fa-solid:handshake"></iconify-icon> ( Support )</h2> <iconify-icon icon="line-md:buy-me-a-coffee-filled"></iconify-icon> {{ form.buy_me_coffee.label_tag}} {{ form.buy_me_coffee}} <iconify-icon icon="simple-icons:patreon"></iconify-icon> {{ form.patreon.label_tag}} {{ form.patreon}} </div> <hr> <div class="genrate text-center"> <button type="submit" class="gen_btn"><iconify-icon icon="bxs:file-md"></iconify-icon> Genrate File</button></div> </form> my views.py for def home(request): if request.method == 'POST': form = Personal_Readme_form(request.POST) if form.is_valid(): form.save() return redirect('personal_readme:preview') else: form = Personal_Readme_form() return render(request, 'home.html', {'form': form}) any suggestion might be helpful -
Django-forms: ValidationError not working / check if attribute exists
I am trying to get an error for the form if name of a created process already exists. Now what happens is that the form just doesn't submit, but it doesn't raise any errors to the form itself noting what is going on. I have looked all different ways to get the ValidationError to do something, but I cannot get it work at all. Form works otherwise as it submits if value doesn't already exist. What am I missing here? Here is models.py class Process(models.Model): name = models.CharField('Process name', max_length=100, unique=True, error_messages={'unique':"Name already in use"}) Here is forms.py class NewProcess(forms.ModelForm): class Meta: model = Process fields = [ 'name', ] def __init__(self, *args, **kwargs): super(NewProcess, self).__init__(*args, **kwargs) def clean_name(self): process_name = self.cleaned_data.get('name') existing = Process.objects.filter(name=process_name).exists() if existing: raise forms.ValidationError(u"Name already in use") return process_name Here is views.py def process_create(request, *args, **kwargs): createprocess = NewProcess(request.POST or None) processes = Process.objects.all() if request.method == 'POST': createprocess = NewProcess(request.POST) if createprocess.is_valid(): process = createprocess.save(commit=False) #other functions here creatprocess.save() context = { 'processes':processes, } return render(request, "process/process-list.html", context) context = { 'createprocess':createprocess, } return render(request, "process/process-create.html", context) -
Django Error: 'WSGIRequest' object has no attribute 'order'
I'm trying to render out the get_cart_total to the email template I'm working on, which gets sent when the success view is triggered and the boolean is True, currently it gets an error message saying 'WSGIRequest' object has no attribute 'order', what's causing this and how do I fix it? Model class Customer(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, blank=True, null=True) email = models.EmailField(max_length=150) class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) @property def get_cart_total(self): orderitems = self.orderitem_set.all() total = sum([item.get_total for item in orderitems]) return total Views def success(request): if order.complete == True: email = request.user.customer.email #error cart_total = request.order.get_cart_total html_message = render_to_string('check/emails/test.html', {'cart_total': cart_total}) recipient_list = [email, ] send_mail( subject, plain_message, email_from, recipient_list, html_message=html_message ) Traceback Traceback (most recent call last): File "D:\test\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "D:\test\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\test\shop\views.py", line 364, in success cart_total = request.order.get_cart_total AttributeError: 'WSGIRequest' object has no attribute 'order' -
I have HTML page stored in javascript variable how to show it in the page
this is my variable have HTML code fetched from database const z = " <div id="div_idadnan"><div class="accordion" id="accordionExample0"><div class="accordion-item"> <h2 class="accordion-header" id="headingOne"><button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#collapseOneadnan" aria-expanded="true" aria-controls="collapseOne">adnan</button></h2><div id="collapseOneadnan" class="accordion-collapse collapse show" aria-labelledby="headingOne" data-bs-parent="#accordionExample0">"<div style="background-color:#eecf9e" class="accordion-body" id="adnan"><table class="table table-bordered border-primary"><thead><tr><th style="font-size:20px;" scope="col">اللاعب</th><th style="font-size:20px;" scope="col">الحرف </th> <th style="font-size:20px;" scope="col">إسم </th><th style="font-size:20px;" scope="col">إسم بنت</th><th style="font-size:20px;" scope="col">حيوان </th><th style="font-size:20px;" scope="col">نبات </th><th style="font-size:20px;" scope="col">جماد </th><th style="font-size:20px;" scope="col">بلاد </th><th style="font-size:20px;" scope="col">الغرفة </th><th style="font-size:20px;" scope="col">مجموع </th></tr></thead><tbody id="divvadnan"><tr><th scope="row">⭐<button id="removeme" type="button" onclick="userremove('adnan')" class="btn btn-primary btn-rounded" data-hover="CLICK ME" data-active="IM ACTIVE"><span>adnan</span></button> </th><td style="font-size:18px;" id="letter">ق</td><td style="font-size:18px;" id="noun">ق</td><td style="font-size:18px;" id="gnoun">ق</td><td style="font-size:18px;" id="animalNoun">ق</td><td style="font-size:18px;" id="plants">ق</td><td style="font-size:18px;" id="inanimate">ق</td><td style="font-size:18px;" id="countries">ق</td><td style="font-size:18px;" id="room">1234567</td><td style="font-size:18px;" id="sum">NaN</td></tr><tr><td scope="row"></td><td scope="row"></td><td><select style="font-size:16px;" onchange="OnSelectedIndexChange('adnan','noun_result')" id="noun_resultadnan" disabled=""><option style="font-size:16px;" href="#">0</option> <option style="font-size:16px;" href="#">5</option><option style="font-size:16px;" href="#">10</option></select><div id="noun_resulttdadnan"></div></td><td><select style="font-size:16px;" onchange="OnSelectedIndexChange('adnan','gnoun_result' )" id="gnoun_resultadnan" disabled=""><option style="font-size:16px;" href="#">0</option> <option style="font-size:16px;" href="#">5</option><option style="font-size:16px;" href="#">10</option></select><div id="gnoun_resulttdadnan"></div></td><td><select style="font-size:16px;" onchange="OnSelectedIndexChange('adnan','animal_result')" id="animal_resultadnan" disabled=""><option style="font-size:16px;" href="#">0</option> <option style="font-size:16px;" href="#">5</option><option style="font-size:16px;" href="#">10</option></select><div id="animal_resulttdadnan"></div></td><td><select style="font-size:16px;" onchange="OnSelectedIndexChange('adnan','plants_result')" id="plants_resultadnan" disabled=""><option style="font-size:16px;" href="#">0</option> <option style="font-size:16px;" href="#">5</option><option style="font-size:16px;" href="#">10</option></select><div id="plants_resulttdadnan"></div></td><td><select style="font-size:16px;" onchange="OnSelectedIndexChange('adnan','countries_result')" id="countries_resultadnan" disabled=""><option style="font-size:16px;" href="#">0</option> <option style="font-size:16px;" href="#">5</option><option style="font-size:16px;" href="#">10</option></select><div id="countries_resulttdadnan"></div></td><td><select style="font-size:16px;" onchange="OnSelectedIndexChange('adnan','inanimate_result')" id="inanimate_resultadnan" disabled=""><option style="font-size:16px;" href="#">0</option> <option style="font-size:16px;" href="#">5</option><option style="font-size:16px;" href="#">10</option></select><div id="inanimate_resulttdadnan"></div></td><td class="success" id="sumadnan">0</td></tr><button type="submit" class="btn btn-primary" id="calcadnan" onclick="calc('adnan' , 'ق' , 'ق' ,'ق','ق','ق','ق','ق','1234567')" style="">Calculate</button></tbody></table></div></div></div></div></div><div id="div_idkaram"><div class="accordion" id="accordionExample1"><div class="accordion-item"> <h2 class="accordion-header" id="headingOne"><button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#collapseOnekaram" … -
Django - Stop Page from reloading after GET Request
I'd like to show all grades from one user on Button Click. Now I wanted to integrate an expandable Button from Bootstrap. The GET Request works perfectly, but the JavaScript for the expandable Button gets triggered on Button Click and then the Page gets reloaded. That means the Button now is back at the original state. Do you guys maybe have a way to fix that? noten.html {% if subject_list %} <form name="subject-list" method="GET"> <ul> {% for subject in subject_list %} <p> <button class="btn btn-primary" type="submit" data-bs-toggle="collapse" data-bs-target="#{{ subject }}" aria-expanded="false" aria-controls="collapseExample" value="{{ subject }}" id="{{ subject }}" name="subject"> {{ subject }} </button> </p> <div class="collapse" id="{{ subject }}"> <div class="card card-body"> {% if grades %} {% for grade in grades %} <li>{{ grade }}</li> {% endfor %} {% else %} <p>Du hast keine Noten in diesem Fach!</p> {% endif %} </div> </div> {% endfor %} </ul> </form> {% endif %} views.py def noten(request): if request.user.is_authenticated: # if user is logged in object_list = Subject.objects.order_by('name') subject_list = [] for subject in object_list: subject_list.append(subject.name) if request.method == 'GET': subject = request.GET.get('subject', '') if subject != '': print(f"GET {subject}") grades = Test.get_grades(student=request.user.id, subject=subject, self=Test) return render(request, 'noten.html', {'subject_list': subject_list, 'grades': grades}) else: … -
Python inside a virtualenv is broken (Django)
TL;DR - Microsoft Store Apps are broken (0 bytes), hence the Python interpreter is unable to create process and run "Python" inside virtualenv, I failed to follow numerous explanations of how to change virtualenv path for Python. Recently, without any changes to my computer/environment, an issue started occurring when executing (also tried python3, which brings the same): python manage.py runserver This brought back the following issue: Unable to create process using '"C:\Users\MyUser\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\python.exe"' As I dug deeper, I realized that all of the apps installed under this folder are 0 bytes, hence they are completed broken, all of a sudden. Therefore I figured it's not an issue with Django, rather the python itself. I tried changing the virtualenv path for Python.exe, instead of using WindowsApps version, I installed the original Python from the original website. I failed to do so, multiple times. I tried: "https://stackoverflow.com/questions/4757178/how-do-you-set-your-pythonpath-in-an-already-created-virtualenv/47184788#47184788" - Adding the path inside "activate" and "activate.bat", as set PYTHONPATH="C:\Users\MyUser\AppData\Local\Programs\Python\Python310\python.exe" And the issue persists. I tried every solution/article I found in regards to the issue I have. Many of them claim a simple result, whereas the rest claim a complete refactor is required. Even downloading from Microsoft store is broken, it always fails. Since I'm … -
Django models foreign key validation
I have the following Django models: class Owner(models.Model): name = models.CharField(max_length=30) class Dog(models.Model): name = models.CharField(max_length=30) owner = models.ForeignKey(Owner) class GoForAWalk(models.Model): date = models.DateTimeField() location = models.CharField() owner = models.ForeignKey(Owner) dog = models.ForeignKey(Dog) I want that a Owner can only GoForAWalk with one of his own Dog. Currently any owner can go for a walk with any dog. Would you restrict this via model validators or via some logic during the creation of a new GoForAWalk object? Can anyone provide an example? I'm quite stuck. Thanks a lot! Cheers, Philipp -
Why does Django debugger keep saying the variable is 'None' when its not?
I have a problem with Django sessions. I am trying to create a clinic website which has a booking functionality so users can book their appointments online. Unfortunately the Django sessions not working properly! The booking is in two steps: Getting the first two datas which are: 'service' and 'day'. Then showing the user the hours (time) available in that day for user to choose for appointment. In the first step in the booking process I get the datas "day" and "service" and then store it in the session so I can check what hour (time) is free in that day and only show the ones that are not booked before. But when we move to the second step of the booking process Django raises a ERROR that the 'day' and 'service' data are 'None'! but they are not 'None' as shown in the 'Debug picture2' link at the end of this question. Views.py: from django.shortcuts import render, redirect from datetime import datetime, timedelta from .models import * from django.contrib import messages def tehranBooking(request): today = datetime.now() minDate = today.strftime('%Y-%m-%d') deltatime = today + timedelta(days=21) strdeltatime = deltatime.strftime('%Y-%m-%d') maxDate = strdeltatime times = [ "3 PM", "3:30 PM", "4 PM", … -
Override error from django image extensions in models
I want to get my custom error from validate_image this is my models.py def validate_image(image): valid_image_extensions = ['jpg', 'png', 'jpeg'] input_extension = str(image).split('.')[1] if input_extension not in valid_image_extensions: raise ValidationError( f"We aren't accepted your extension - {input_extension} only accepted {','.join(valid_image_extensions)}" ) class Image(models.Model): description = models.CharField(null=True, default='Image', blank=True, max_length=120) image = models.ImageField(upload_to='images', validators=[validate_image]) When i try upload image with .raw extension i expected my custom validation but i have error from django. { "image": [ "File extension “raw” is not allowed. Allowed extensions are: bmp, dib, gif, tif, tiff, jfif, jpe, jpg, jpeg, pbm, pgm, ppm, pnm, png, apng, blp, bufr, cur, pcx, dcx, dds, ps, eps, fit, fits, fli, flc, ftc, ftu, gbr, grib, h5, hdf, jp2, j2k, jpc, jpf, jpx, j2c, icns, ico, im, iim, mpg, mpeg, mpo, msp, palm, pcd, pdf, pxr, psd, bw, rgb, rgba, sgi, ras, tga, icb, vda, vst, webp, wmf, emf, xbm, xpm." ] } How i can run custom validation before django validation ?