Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
my edit page showing nothing besides what already in the main.html
I'm working on a Django project making a to-do list app in my edit page nothing is showing besides what is already inside my main.html my edit.html file {% extends 'main.html' %} {% block container %} <div>editor</div> <div> {% if item %} <form class="form-check-inline my-2 my-lg-0" method="POST"> {% csrf_token %} <input class="form-control mr-sm-2" type="search" placeholder="{{ item.item }}" aria-label="search" value="{{ item.item }}" name="item"> <input type="hidden" value="{{item.complete}}" name="complete"> <button clss="btn btn-outline-sceondary my-2 my-sm-0" type="submit">Submit</button> </form> {% endif %} </div> {% endblock %} my views def edit(request, list_id): if request.method == "POST": item = List.objects.get(pk=list_id) form = ListForms(request.POST or None, instance=item) if form.is_valid(): form.save() messages.success(request,('Item has been Edited')) return redirect('home') #return render(request, 'home.html',{'all_item': all_item}) else: item = List.objects.get(pk=list_id) return render(request, 'home.html',{'item': item}) my URLs from django import views from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('delete/<list_id>', views.delete, name='delete'), path('crossoff/<list_id>', views.crossoff, name='crossoff'), path('uncrossoff/<list_id>', views.uncrossoff, name='uncrossoff'), path('edit/<list_id>', views.edit, name='edit'), ] if you need any more information just ask me in the comment -
Host a Django project on Apache2 locally
I have finished a Django project and want to deploy it over Apache2 locally over LAN. I have figured out how to connect Django with Apache2 using mod_wsgi and it worked great because I was able to use Apace2 to actually host Django on localhost. Now I want to actually make this project available to anyone on my local network. Like for instance assuming that my local IP address was 10.10.10.51 I could go to a different device connected to my local network and type in 10.10.10.51 to actually get to the Apache2 server homepage. It does that successfully. My Django project is hosted on my Apache2 localhost server at djangoproject.localhost and it works fine just on my PC. When I move on to the other PC and go to djangoproject.localhost the site is not up there. Yes they are both connected to the same LAN network. I used this tutorial to host Django on Apache2: Host Django on Apache2 with mod_wsgi -
Why django can't read my path url to show the book list?
I made some objects on my local library site and trying to go in this link: catalog/books/ to see my Booklist, but the result: enter image description here also my codes : urls.py: from django.urls import path from django.contrib import admin from . import views app_name='catalog' urlpatterns = [ path(r'^$', views.Index.as_view(), name='index'), path(r'^books/$', views.BookListView.as_view(), name='books'), path(r'^book/(?P<pk>\d+)$', views.BookDetailView.as_view(), name='book-detail'), ] my html files: enter image description here enter image description here also i add catalog: in my models in def get_absolute_url -
Django: How i can dislay the resulat of some calculation after press a button on the same page
i want to display the result of some calculation after click on a button, the thing that I have go and call the fields-calculated after calculation in the same template html. but the result is gone to another page because i have specified on the urls.py another route url. Here is the code of the 2 functions: one is for calculation and the other one is for the home page (where is contain the fields-data that i have entered and the button of calculation), and i want to display there the result of calculation that i have did on the first function in the views.py: @login_required def calcul_resultat(request): resultat = float(0) ch_permanent = request.POST.get('ch_permanent', False) ch_exp = request.POST.get('ch_exp', False) calcul="" calcul_exp="" calcul_md="" if not (ch_permanent and ch_exp): return HttpResponse({"result" :resultat}) else: float_ch_exp = float(ch_exp) resultat = 2.4 * float_ch_exp calcul += "<strong>Calculation of Dweight: </strong>" calcul += str(resultat) float_ch_permanent = float(ch_permanent) resultat = 3.6 * float_ch_permanent calcul_exp += "<strong>Calculation of the load: </strong>" calcul_exp += str(resultat) float_calcul_exp = float(2.4 * float_ch_exp) float_calcul_per = float(3.6 * float_ch_permanent) float_length = float(length) resultat += (float_calcul_exp * float_length) calcul_md += "<strong>Calculation moment </strong>" calcul_md += str(resultat) return render(request,'pages/home.html',{'calcul':calcul, 'calcul_exp':calcul_exp, 'calcul_md':calcul_md}) and Here it is … -
Django GeoIP2 libmaxmind c library in a docker container
I use GeoIP2 in a dockerised Django app and am looking to improve the performance of the IP lookups. The Django documentation says: Additionally, it is recommended to install the libmaxminddb C library, so that geoip2 can leverage the C library’s faster speed. Could somebody please provide a working example of how to do this in a docker container? I am using a Django Cookiecutter template, which uses docker-compose and a python image in the Django Dockerfile: ARG PYTHON_VERSION=3.9-slim-bullseye FROM python:${PYTHON_VERSION} as python FROM python as python-build-stage ARG BUILD_ENVIRONMENT=local I'm currently using GeoIP2 like this in views.py, and it does not perform well: from django.contrib.gis.geoip2 import GeoIP2 from ipware import get_client_ip class CheckInView(View): def get(self, request, pk): if client_ip and is_routable: client_ip, is_routable = get_client_ip(request) g = GeoIP2() city_dict = g.city(checkin.ip) checkin.city = city_dict['city'] checkin.post_code = city_dict['postal_code'] checkin.region = city_dict['region'] checkin.country_code = city_dict['country_code'] checkin.country_name = city_dict['country_name'] lat_lon = g.lat_lon(client_ip) checkin.lat = lat_lon[0] checkin.lon = lat_lon[1] ... return HttpResponseRedirect(...) I'm requesting a working example because there is a lot I don't know: not familiar with compiling stuff in c, not familiar with how to use c from python, and definitely not familiar with how to do these things inside a docker … -
Django Registration - Checks if a user already exists
The web app currently should be able to register new users. However, should a user already exists, it should redirect user to the login page with a message of "User already exists!". The Django views: def registerPage(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): email = form.cleaned_data['email'] username = form.cleaned_data['username'] if User.objects.filter(username=username).exists(): messages.info( request, 'User already exists! Try logging in.') return redirect('login') else: user = form.save(commit=False) raw_password = User.objects.make_random_password() user.set_password(raw_password) user.save() ... I filter the user by his/her username and checks if it already exists by using the exists() method. This doesn't seem to work though. Is there something I'm missing? -
how to setup liveness model in face recognition employee attendance system ---python
I am new to programming and, I am building a real-time face recognition employee attendance system for a company in python, but I can not set up the liveness model(anti-spoofing), how can I do that pls help me thank you all, here below is code for face detecting during check-in time def mark_your_attendance(request): detector = dlib.get_frontal_face_detector() predictor =dlib.shape_predictor('face_recognition_data/shape_predictor_68_face_landmarks.dat') svc_save_path="face_recognition_data/svc.sav" with open(svc_save_path, 'rb') as f: svc = pickle.load(f) fa = FaceAligner(predictor , desiredFaceWidth = 96) encoder=LabelEncoder() encoder.classes_ = np.load('face_recognition_data/classes.npy') faces_encodings = np.zeros((1,128)) no_of_faces = len(svc.predict_proba(faces_encodings)[0]) count = dict() present = dict() log_time = dict() start = dict() for i in range(no_of_faces): count[encoder.inverse_transform([i])[0]] = 0 present[encoder.inverse_transform([i])[0]] = False vs = VideoStream(src='http://192.168.137.127:8080/video').start() sampleNum = 0 while(True): frame = vs.read() frame = imutils.resize(frame ,width = 800) gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = detector(gray_frame,0) for face in faces: print("INFO : inside for loop") (x,y,w,h) = face_utils.rect_to_bb(face) face_aligned = fa.align(frame,gray_frame,face) cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),1) (pred,prob)=predict(face_aligned,svc) if(pred!=[-1]): person_name=encoder.inverse_transform(np.ravel([pred]))[0] pred=person_name if count[pred] == 0: start[pred] = time.time() count[pred] = count.get(pred,0) + 1 if count[pred] == 4 and (time.time()-start[pred]) > 1.2: count[pred] = 0 else: #if count[pred] == 4 and (time.time()-start) <= 1.5: present[pred] = True log_time[pred] = datetime.datetime.now() count[pred] = count.get(pred,0) + 1 print(pred, present[pred], count[pred]) cv2.putText(frame, str(person_name)+ str(prob), (x+6,y+h-6), cv2.FONT_HERSHEY_SIMPLEX,0.5,(0,255,0),1) … -
Django Rest Framework Am I doing it right?
I have studied DRF myself and one question bothers me, unfortunately I have no one to ask and this question bothers me all the time. Is writing application logic in views (as in the attached code) a good approach? When sending a query to the server with the intention, for example, to accept an order, I have to update the values from models other than the order or carry out validation of statuses, change the data on their basis. In the first tutorials from which I learned, among others, JustDjango all logic is in the view. However, after writing some code and watching other tutorials, I feel that this is not the right approach. Should not save and update models be done through a serializer? If so, whether through one large serializer or several smaller serializers. class ZK_AddUpdateItemWithInstaReservation(APIView): permission_classes = (IsAuthenticated,) def post(self, request, *args, **kwargs): pzitem_id = request.data.get('pzitem_id') ordered_quantity = request.data.get('ordered_quantity') order_id = request.data.get('order_id') user_id = request.data.get('user_id') item_id = request.data.get('item_id') if ordered_quantity: if int(ordered_quantity) < 0: return Response({'error': 'Próbujesz zamówić ujemną wartość'}) try: item = Item.objects.get(id=item_id) except: return Response({'error': 'Item with given id does not exists'}) try: order = Order.objects.get(id=order_id) except: return Response({'error': 'Order with given id does not … -
Add filters to autocomplete fields in django
I have a question about autocomplete fields in django. Let's assume we have these 2 models: class Animal: name = models.CharField() is_big = models.BooleanField() class Human: pet = models.ForeignKey(Animal) And then we have the admin file which looks something like this: class HumanAdmin(admin.ModelAdmin): autocomplete_fields = ['pet'] def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == 'pet': kwargs["queryset"] = Animal.objects.filter(is_big=True) return super().formfield_for_foreignkey(db_field, request, **kwargs) class AnimalAdmin(admin.ModelAdmin): search_fields = ['name'] admin.site.register(Animal, AnimalAdmin) admin.site.register(Human, HumanAdmin) What I wanted to achieve here is to have in the animal selection dropdown only the big animals which worked, and then I decided to make that filed an autocomplete one but after making it autocomplete it seems to be ignoring my formfield_for_foreignkey filter, it is now loading all the animals. And I wanna ask how should I combine these two properly? I want an autocomplete field for animals, but I want it to consider only those who have is_big == True . My idea is that I should somehow capture what is entered on the autocomplete textfield and add that to my filtering but I'm not sure how to do that. -
How do I livestream the video I have captured using OpenCV on my webpage which is made using Django while also keeping the face recognition function
I am a new developer working at an interI am developing a web application which takes your attendance using face recognition and puts the entry in the database using django, python, open-cv and the face_recognition library of python. The Login page looks like this: Login Page. When I click the login button, my views program directs to an external python function which opens a separate camera window which does the face recognition. The Camera Window. What I want to do is display the camera directly in the browser window rather than as a separate window. I found some tutorials and also tried to implement them but using them I can only display the frames in the browser window while the functionality of face recognition is lost. The Views Code (views.py): def camera_on(request): out = Popen('E:/Study/Internship/Capstone/Project/Web App/web_app/Basic.py', shell=True, stdout=PIPE) op = out.stdout.read().decode("utf-8") new_str = '' for i in range(len(op)-2): new_str += op[i] request.session['name'] = new_str return render(request, 'open_camera.html', {'data': new_str}) This code accesses the Basics.py file which opens the camera window, does the face recognition and gives the entry in the database. The Basics.py code: from datetime import datetime, date import os import django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'web_app.settings') django.setup() import cv2 import face_recognition … -
How to display choices in a django form based on a database
I am writing a django application that helps create a shopping list based on the store stock. The store stock will be stored as a database that looks like this (please ignore spelling errors!): Type Name Colour Fruit Apple Pink Fruit Apple Green Fruit Banana Yellow Fruit Banana Green Fruit Clementine Orange Fruit Blueberry Blue Veg Tomato Red Veg Spinach Dark green Veg Kale Dark green Veg Dwarf beans Light green From this store stock, a user can create a shopping list by choosing the above three fields using a form. The user will first choose the type - which should be displayed as a choice between "Fruit" or "Veg". Then when they choose "Fruit" for example, only the fruits should be provided as choices in "Name". Finally, for them to choose colour, only the corresponding colour of the chosen fruit should be displayed as the options in the form. To create the store stock database, the form I created is as follows: Class Stock(models.Model): Type_choices = models.TextChoices('Fruit','Veg') stock_type = models.CharField(choices=Type_choices.choices) name = models.CharField(max_length=264, unique=False) colour = models.CharField(max_length=264, unique=False) I then populated it to look like the above table. To store the shopping list, I created a model: Class ShoppingList(models.Model): … -
Render seaborn Plot on Django Template
I am trying to render the plot generated by seaborn on Django template. I have the following code in my views.py: import matplotlib.pyplot as plt import seaborn as sns from io import BytesIO import base64 def heat_map_plot(): df = data.corr() plot = sns.heatmap(data=df) buffer = BytesIO() plot.savefig(buffer, format='png') graphic = base64.b64encode(buffer.getvalue()) return graphic in stats.html: <li><img src='data:image/png;base64,{{heat_map_plot}}'/></li> but show empty png in the template, why? -
How to add extra key in created object in Django Rest Framework?
I'm new to Django Currently I'm trying to add a simple extra key on my returned json in the serializer. Here's the create() override of my serializer: def create(self, validated_data): available_dates = validated_data.pop("available_dates") # Default expiry time is 3 days expiry = datetime.datetime.now() + datetime.timedelta(days=3) event = Events.objects.create(**validated_data, expiry=expiry) for selectedTime in available_dates: AvailableDates.objects.create( event=event, **selectedTime, ) signer = Signer() signedObject = signer.sign_object( {"expiry": expiry.isoformat(), "id": event.id} ) return {**event, "signed_url": signedObject} As you can see, I don't want to only return event, but I want to add a signed url. This gave me an error: 'Events' object is not a mapping So then how do I add extra key? What do I return in the create function? Can I create Response() as the return of create function in DRF? -
Installing mod_wsgi with pip install causes an error
I am trying to install mod_wsgi so I can run my Django app with Apache. However when I use pip install mod_wsgi I get the following error: ERROR: Command errored out with exit status 1: command: 'C:\Program Files\Python310\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Admin\\AppData\\Local\\Temp\\pip-install-_w59fztq\\mod-wsgi_5a0ae0135da94aadbb09b85297022451\\setup.py'"'"'; __file__='"'"'C:\\Users\\Admin\\AppData\\Local\\Temp\\pip-install-_w59fztq\\mod-wsgi_5a0ae0135da94aadbb09b85297022451\\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\Admin\AppData\Local\Temp\pip-record-mwvtbeia\install-record.txt' --single-version-externally-managed --user --prefix= --compile --install-headers 'C:\Users\Admin\AppData\Roaming\Python\Python310\Include\mod-wsgi' cwd: C:\Users\Admin\AppData\Local\Temp\pip-install-_w59fztq\mod-wsgi_5a0ae0135da94aadbb09b85297022451\ Complete output (24 lines): running install running build running build_py creating build creating build\lib.win-amd64-3.10 creating build\lib.win-amd64-3.10\mod_wsgi copying src\__init__.py -> build\lib.win-amd64-3.10\mod_wsgi creating build\lib.win-amd64-3.10\mod_wsgi\server copying src\server\apxs_config.py -> build\lib.win-amd64-3.10\mod_wsgi\server copying src\server\environ.py -> build\lib.win-amd64-3.10\mod_wsgi\server copying src\server\__init__.py -> build\lib.win-amd64-3.10\mod_wsgi\server creating build\lib.win-amd64-3.10\mod_wsgi\server\management copying src\server\management\__init__.py -> build\lib.win-amd64-3.10\mod_wsgi\server\management creating build\lib.win-amd64-3.10\mod_wsgi\server\management\commands copying src\server\management\commands\runmodwsgi.py -> build\lib.win-amd64-3.10\mod_wsgi\server\management\commands copying src\server\management\commands\__init__.py -> build\lib.win-amd64-3.10\mod_wsgi\server\management\commands creating build\lib.win-amd64-3.10\mod_wsgi\docs copying docs\_build\html\__init__.py -> build\lib.win-amd64-3.10\mod_wsgi\docs creating build\lib.win-amd64-3.10\mod_wsgi\images copying images\__init__.py -> build\lib.win-amd64-3.10\mod_wsgi\images copying images\snake-whiskey.jpg -> build\lib.win-amd64-3.10\mod_wsgi\images running build_ext building 'mod_wsgi.server.mod_wsgi' extension error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/ ---------------------------------------- ERROR: Command errored out with exit status 1: 'C:\Program Files\Python310\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Admin\\AppData\\Local\\Temp\\pip-install-_w59fztq\\mod-wsgi_5a0ae0135da94aadbb09b85297022451\\setup.py'"'"'; __file__='"'"'C:\\Users\\Admin\\AppData\\Local\\Temp\\pip-install-_w59fztq\\mod-wsgi_5a0ae0135da94aadbb09b85297022451\\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; … -
How to disable specific change_actions button in Django admin?
I have a set of change_actions buttons on my Django Admin page: A part of code for this particular InvoiceAdmin page: def invoice_lines_link(self, request, obj): """ Set a button to the page of the Invoice's Invoice lines in the details view """ return HttpResponseRedirect("{url}?invoice__pk={pk}".format( url=reverse("admin:backend_invoiceline_changelist"), pk=obj.pk )) invoice_lines_link.label = "Invoice Lines" def customer(self, request, obj): """ Set a button to the page of the InvoiceLine's Customer in the details view """ return HttpResponseRedirect(reverse( "admin:backend_customer_change", args=[obj.customer.id] )) change_actions = ('customer', 'invoice_lines_link', 'test_link', 'pdf',) I would like to have a button disabled, when other action in called. How can i refer to that button and disable it? It is not in a form and not marked as a action, so both get_form() and admin.site.disable_action wont work. (I want to disable one of the grey buttons, that you can notice on the picture - it is not related to the form) -
Get back access to the development server
I ran manage.py check --deploy¶ for my django project before I was actually ready to deploy and now I can't seem to run python3 manage.py runserver for any of my projects. Is there anyway to reverse my actions? This is the error I get in my terminal whenever I try to access a project in my browser. code 400, message Bad request version ('\x9a\x9a\x13\x01\x13\x02\x13\x03À+À/À,À0̨̩À\x13À\x14\x00\x9c\x00\x9d\x00/\x005\x01\x00\x01\x93êê\x00\x00\x00\x17\x00\x00ÿ\x01\x00\x01\x00\x00') [10/Feb/2022 11:33:40] You're accessing the development server over HTTPS, but it only supports HTTP. -
Django models with mutually exclusive references
I think I have this completely muddled in my head and would like some help please. I am new to this, so be gentle. I have a model of a transformer core: class Core(models.Model): name = models.CharField(max_length=100, default="") laminations = models.ForeignKey(Lamination, on_delete=models.CASCADE) ccore= models.ForeignKey(Ccore, on_delete=models.CASCADE) stack = models.FloatField() stack_factor = models.FloatField(default=0.92) def __str__(self): return self.name I don't think I am doing this correctly. A Core can have either a lamination OR a ccore but not both. How do I set up the relationship between Core and lamination and ccore so that I can select which one (maybe late on a different type as well) is valid? I thought of having a selection called core_type, that the front end would then be able to change, and depending on this selection one of these ForeignKeys is set to NULL. But that feels wrong to me. -
How to validate xl data in django
Example: username is string not int and, id int not string? This is my code: class UploadPersonView(APIView): permission_classes = [IsAuthenticated,IsAdminPermission|IsSuperAdminPermission] serializer_class = PersonUploadSerializer def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) dataset = Dataset() file = serializer.validated_data['file'] try: imported_data = dataset.load(file.read(), format='xlsx') '''uploading xl file with particular data what user mentioned in xl we are looping the xl data and appending into the database with same fields''' for data in imported_data: -
Python(Django): form write an ERROR befor submit
I want to check the Form after submit, but I have ERROR MASSAGE befor it. I thing there is a mistake at VIEW-file this is my views.py: @login_required def post_create(request): form = PostForm(request.POST) template = 'posts/create_post.html' if request.method == 'POST': if form.is_valid(): form.instance.author = request.user form.save() return redirect('posts:profile', username=request.user.username) return render(request, template, {'form': form}) this is my HTML template: {% if form.errors %} {% for field in form %} {% for error in field.errors %} <div class="alert alert-danger"> {{ field.label }}: {{ error|escape }} </div> {% endfor %} {% endfor %} {% for error in form.non_field_errors %} <div class="alert alert-danger"> {{ error|escape }} </div> {% endfor %} {% endif %} -
What is the output format of datefield to us it in strptime?
I need to display three upcoming college fests in homepage, so I need to compare start_date of each fest with today's date and display it if it's equal or greater than today's date The code I need this for is(here start_date is of type DateField) def home(request): context={ 'fests':Fest.objects.all().filter(datetime.strptime('start_date',"%b %d ")>=date.today()).order_by('-start_date')[:3] } return render(request,'webpage/home.html',context) The output of start_date is in str form, so I can't compare it with date.today(). To use strptime() I need to input the format of the string. So what is the format needed? -
Return name of file after converting from html to pdf using pdfkit
I have converted some html to pdf successfully. I need to return the name of the pdf file so that I can attach it and send it via email. Function that converts to pdf. def generate_pdf_statement( entries: list,start_date: str, end_date: str, patient_id: int ): auth = authenticate() patient_details = get_patient_details(auth["key"], patient_id) # html_content = get_template(f"statements/{cust_type}_statements.html").render( html_content = get_template("email/patient_statements.html").render( { "start_date": start_date, "end_date": end_date, "patient_email": patient_details.get("patient_address") and patient_details.get("patient_address")[0] and patient_details.get("patient_address")[0].get("email"), "patient_phone": patient_details.get("patient_address") and patient_details.get("patient_address")[0] and f"+{patient_details.get('patient_address')[0].get('callingcode')}{patient_details.get('patient_address')[0].get('phone')}", "patient_name": patient_details.get("name"), "entries": entries, } ) file = pdfkit.from_string(html_content,"out.pdf") return file This is where I send my email: pdf_report = generate_pdf_statement(statement_entries,start_date,end_date,patient_id) firstname = user and user.first_name or "" message = render_to_string(REPORT_DOWNLOAD_TEMPLATE, {"name": firstname}) email_send( subject="Patient statements Download Success", body=message, _from=settings.EMAIL_HOST_USER, _to=email, _file_attachment=pdf_report ) logger.info("Patient statements sent successfully to user") However, the value of file returned is a boolean true. And if I do this by not specifying the name I get bytes returned pdfkit.from_string(html_content,"out.pdf") I need to save the name and return the file name so I can attach -
Angular Block Register Page
I was Wonderring is there a way to make register url not working when user is logged in. I am use Frontend Angular And Backend Django -
APPEND_SLASH doesn't work for me with Django 4
Django version 4.0.2 settings.py 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', ] APPEND_SLASH = True project's urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('poolapp.urls')), ] app's urls.py urlpatterns = [ path('index/', index, name="index"), ] With the same configuration, If I visit 127.0.0.1/index , Django 3.x redirects me to 127.0.0.1/index/ . Django 4.0.2 returns 404. Did something change with Django 4.x? -
"NotImplementedError at /myfile/download/8" while downloading zip file in Django
I am trying to download zip file which contains multiple files in same or different formats. This zip file get downloaded after clicking on a button "Download". This functionality works perfectly on local development server. But after deploying the web app on Google cloud it throws "NotImplementedError at /myfile/download/8" This backend doesn't support absolute paths. ... Cloud storage has respective path with the file still it is not working, why? Everything is working fine on local machine, but fails on production, why? Please help! Thanks in advance. -
Django REST on Heroku with Server Error (500)
I made my django website RESTful, but i can only see the endpoint when debug=True. When I switch to false it gives an Server Error (500). The app is deployed on heroku. I tried to use different permissions as "AllowAny" and "IsAuthenticatedOrReadOnly" in views.py and added them also in settings.py under REST_FRAMEWORK. Any ideas what the problem could be?