Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How have django async views changed in 3.2?
I've been learning how to use django for the past few weeks, and was looking into async view tutorials to try to see how they worked. I was watching one by Pyplane and noticed that the code no longer ran asynchronously. I looked into the documentation a bit more and it seemed like what he showed should have worked. I also tried hard coding it with asyncio and it gave me a SynchronousOnlyOperation error. Does anyone know a fix? Thanks in advance! views.py from django.http import HttpResponse from asgiref.sync import sync_to_async, async_to_sync import asyncio import time from movies.models import Movie from stories.models import Story # Utils def get_movies(): print("Prepare to get the movies") time.sleep(2) qs = Movie.objects.all() print(qs) print("All movies retrieved") def get_stories(): print("Prepare to get the stories") time.sleep(5) qs = Story.objects.all() print(qs) print("All stories retrieved") @sync_to_async def get_movies_async(): print("Prepare to get the movies") time.sleep(2) qs = Movie.objects.all() print(qs) print("All movies retrieved") @sync_to_async def get_stories_async(): print("Prepare to get the stories") time.sleep(5) qs = Story.objects.all() print(qs) print("All stories retrieved") # Views def home_view(request): return HttpResponse('<h1>Hello, World!</h1>') def main_view(request): start_time = time.time() get_movies() get_stories() total_time = time.time() - start_time print(f"Sync Execution time: {total_time} second(s)") return HttpResponse('<h1>Sync</h1>') async def main_view_async(request): start_time = time.time() … -
How to display error messages for multiple forms, including formsets?
Say I'm rendering a template that has multiple forms on it. The one im having issue with at the moment, I am rendering a modelform, and a formset. return render(request, "dansapp/backtest.html", { "form": form, "formset": formset }) Both forms have custom clean() methods too, just for the record. In my layout.html, I have the run of the mill code for displaying any and all form errors. It works like a charm, so long as I am rendering a template with a SINGLE form called "form". In my case, with multiple forms, how would I do with without repeating a ludicrous amount of code in my layout? It makes it even worse, because in formsets, you get a list of forms to check (I think). I also need to check the non-error fields for my custom clean() methods. {% for field in form %} {% for error in field.errors %} <div class="alert alert-danger alert-dismissible sticky-top fade show" role="alert"> <strong>{{ field.label }}:</strong> {{ error }} <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button> </div> {% endfor %} {% endfor %} {% for error in form.non_field_errors %} <div class="alert alert-danger alert-dismissible sticky-top fade show" role="alert"> <strong>Validation error:</strong> {{ error }} <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button> </div> … -
python, django: it does not show the price on price_details.html but there is no error message
On website home page User select the airport, suburb and passenger. after that, views.py do function to calcaulate the price with that information. but the price does not appear on price_detail.html here are the codes at views.py def price_detail(request): if request.method == "POST": airport = request.POST.get('airport') suburb = request.POST.get('suburb') passenger = request.POST.get('passenger') data = { 'airport': airport, 'suburb': suburb, 'passenger': passenger, } def price_cal(): if airport == 'To airport': return int(suburbs.get(suburb)) + (int(passenger) * 10) - 10 elif airport == 'From airport': return int(suburb.get(suburb)) + (int(passenger) * 10) return render(request, 'basecamp/price_detail.html', {'price_cal()': price_cal() }, ) else: return render(request, 'basecamp/price_detail.html', {}) I do not know what was wrong... please don't telll me to do django tutorial again... I am new and beginner... that's why I ask quesitons here. Thank you in advance -
How is DRF auth token received in a real world web application
This question might look stupid but I want to get some clarification. I'm building a Django rest framework application for the very first time. I'm able to set up api endpoints for the application. And when I register a user he gets a token. And when I login a user through postman it returns a token. But in real world app, how does the client receive that drf token that is return as json data that is needed to login. Does he receive it in his email that he used to register? Also, if the user recieves the token, am I supposed to create another API to contain the field that the user eventually sends the token through before gaining access to the website? Please I would appreciate it if I also get a good material that explains the process in details and uncomplicated. -
I want to use `django` to do something like the `Github` repository
I want to use django to do something like the Github repository, but I don't know how to do it. -
Problem loading bootstrap-v5 Javascript with Django
I am currently learning Django and bootstrap, and I wanted to test some dropdown features. I looked for a while in my html code seeking for errors but apparently, the problem comes from the javascript and popper libraries of bootstrap that won't load properly. When i'm making a dropdown menu, the dropdown button is displayed, but nothing happens when I click on it. Same for all the features of bootstrap requiring JS such as alerts, toasts.. But strangely, carrousels, for which the docs indicates also they require Javascript, work properly. It doesn't matter how I try to load the JS files, it never works. I tried to load the JS and Popper separately, by including these two lines just before the closing tag : <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.min.js" integrity="sha384-Atwg2Pkwv9vp0ygtn1JAojH0nYbwNJLPhwyoVbhoPwBhjQPR5VtM2+xf0Uwh9KtT" crossorigin="anonymous"></script> </body> I also tried the bundle : <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script> </body> It never worked so I downloaded the bundle and tried to load it this way : <script src="{% static 'js/bootstrap.bundle.js' %}"></script> This doesn't work either. When I place a test.js in the same folder with some junk inside like document.write("test"), I can see than the file is loaded properly. Also, the chrome console doesn't show any … -
Django static (css) and templates folders
I want to organize my the templates and static for each app in project as following: project/ app1/ static/ css/ app1.css templates/ app1_template.html app2/ static/ css/ app2.css templates/ app1_template.html project/ settings.py ... templates/ base.html static/ css/ base.css The intention: base.html uses only css styling from base.css Both app1_template and app2_template.html extend base.html app1_template and app2_template.html use their own .css respectively. My settings.py has these lines: TEMPLATES = [ { ... 'DIRS': [(os.path.join(BASE_DIR, 'templates')),], ... }, }, ] ... STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) In base.html: {% load static %} <!DOCTYPE html> <html> <head> <title>{% block title %}{% endblock %}</title> <link href="{% static "css/base.css" %}" rel="stylesheet"> </head> <body> <div id="content"> {% block content %} {% endblock %} </div> </body> </html> In app1_template.html: {% extends "base.html" %} {% load static %} <link href="{% static "css/app1.css" %}" rel="stylesheet"> With the above setup, my app1_template.htlm does not load app1.css styling at all. If I put the styling from app1.css into base.css, then it loads nicely. What code lines do I change to keep this organization? -
Django- Cannot assign queryset must be a instance
I am trying to make a multiple choice form, but I am getting the error: Cannot assign "<QuerySet [<Session: bbbb>, <Session: jheeyyy>]>": "Booking.session" must be a "Session" instance. I checked some solutions in stackoverflow but I can't solve it. I tried to change ModelMultipleChoiceField as ModelChoiceField but it gives "select a valid choice. that choice is not one of the available choices error." when I did it. I need help. models.py class Booking(models.Model): """ Entry recording a user registration to an event """ event = models.ForeignKey( "Event", related_name="bookings", on_delete=models.CASCADE ) person = models.ForeignKey( settings.AUTH_USER_MODEL, related_name="bookings", on_delete=models.CASCADE ) session = models.ForeignKey( "Session", related_name="bookings", null=True, blank=True, on_delete=models.SET_NULL, ) class Meta: unique_together = ("event", "person") ordering = ["id"] def __unicode__(self): return "{0} : {1}".format(self.event.title, self.person) forms.py class SessionChoiceField(forms.ModelMultipleChoiceField): def label_from_instance(self, obj): return obj.get_label() class BookingSessionForm(ModelForm): session = SessionChoiceField( label="Select your session", queryset=None, required=True, widget = forms.CheckboxSelectMultiple, to_field_name = "title", ) class Meta: model = Booking fields = ["session"] def __init__(self, target_url, *args, **kwargs): super(BookingSessionForm, self).__init__(*args, **kwargs) self.fields["session"].queryset = self.instance.event.sessions.all() self.helper = FormHelper() self.helper.form_method = "post" self.helper.form_action = reverse( target_url, kwargs={"booking_id": self.instance.id} ) self.helper.layout = Layout( "session", FormActions( Submit("save", "Confirm", css_class="btn btn-success"), Reset("reset", "Reset", css_class="btn btn-warning"), ), ) views.py def _booking_update_session(request, booking, form_target_url): """ … -
I am receiving this error when I try to send a file from react to django. (TypeError: __init__() got an unexpected keyword argument 'file')
Please help me solve this error. When I try to get the data on using file_serializer = FileSerializer(request.POST, request.FILES) instead in the picture. I receive error that name field is required even though I have passed it. I am not sure what more I can describe the error but any help would be appreciated. Models.py from django.db import models import uuid # Create your models here. class File_Uploader(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) file = models.FileField(blank=False, null=False, max_length=1000000000) name = models.CharField(max_length=64) upload_date = models.DateTimeField(auto_now=True, db_index=True) size = models.IntegerField(default=0) def __str__(self): return self.file.name Serializer.py from rest_framework import serializers from .models import File_Uploader from django.views.decorators.csrf import csrf_exempt @csrf_exempt class FileSerializer(serializers.ModelSerializer): class Meta: model = File_Uploader fields = ("file", "name", "size") views.py # from django.shortcuts import render from rest_framework.parsers import FileUploadParser, MultiPartParser from rest_framework.response import Response from rest_framework.views import APIView from rest_framework import status from .serializers import FileSerializer class FileUploadView(APIView): permission_classes = [] parser_class = (FileUploadParser,MultiPartParser,) def post(self, request, *args, **kwargs): file_serializer = FileSerializer(data=request.data) if file_serializer.is_valid(): file = file_serializer.data.get("file") name = file_serializer.data.get("name") size = file_serializer.data.get("size") queryset = FileSerializer(file=file, name=name, size=size) queryset.save() return Response(file_serializer.data, status=status.HTTP_201_CREATED) else: return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST) React File Upload Code submit = (e) => { e.preventDefault(); let file = e.target.files[0]; let … -
How to clear a validation error in Django
I have a simple registration page in my Django web application. Once a user signs up, I am able to query my database and see if the username is already in use, if it is, I display a simple ValidationError. My problem is I can't figure out how to remove the error after a few seconds. I'm pretty good with Python but haven't found any luck, the only thing I can find is this outdated article from 2010 that gives me code that doesn't work anymore. This seems like a really simple fix, just import time and run a while statement, but I can't find the docs to remove a validation error. Bellow is my function for recognizing if the username is already in use. Thank you to everyone who helps! def clean(self): cleaned_data=super().clean() if User.objects.filter(username=cleaned_data["username"]).exists(): raise ValidationError("This username is taken, please try another one") -
Prepend URL to all URLs in Django
Was wondering if there was a way to prepend all URLs with a particular URL. I'll explain the challenge, perhaps I'm going about it all wrong: Imagine I have three sites all built using Django that are run using nginx and within separate docker containers: main_site, project1 and project2. When navigating to https://main_site, this should load the pages in main_site as normal. But when navigating to https://main_site/projects/project_1/, This should navigate to project 1. And similarly, when navigating to https://main_site/projects/project_2/, this should load the pages from project 2. I've managed to make this somewhat work using nginx and docker. I have rules something along the lines of: location / { proxy_pass http://main_site; } location /projects/project_1 { proxy_pass http://project_1; } location /projects/project_2 { proxy_pass http://project_2; } This works perfectly for the homepage (minus the static assets). But, whenever we use template tags in Django, the links in creates is always relative to root (/something/), whenever on any link, it takes me back to the main_site. I get why this is happening, because everything is happening on the same port. Question is, is there a way to prepend a URL to all the URLs (static assets as well) without fundamentally having to add … -
What is problems?
TemplateDoesNotExist at / pages/index.html Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.2.4 Exception Type: TemplateDoesNotExist Exception Value: pages/index.html Exception Location: C:\Users\Leroi\Desktop\Ecom_site\Ecomenv\lib\site-packages\django\template\loader.py, line 19, in get_template Python Executable: C:\Users\Leroi\Desktop\Ecom_site\Ecomenv\Scripts\python.exe Python Version: 3.8.5 Python Path: ['C:\Users\Leroi\Desktop\Ecom_site\Ecomenv\ecomsite_web', 'C:\Users\Leroi\Desktop\Ecom_site\Ecomenv\Scripts\python38.zip', 'c:\programdata\anaconda3\DLLs', 'c:\programdata\anaconda3\lib', 'c:\programdata\anaconda3', 'C:\Users\Leroi\Desktop\Ecom_site\Ecomenv', 'C:\Users\Leroi\Desktop\Ecom_site\Ecomenv\lib\site-packages'] Server time: Sat, 05 Jun 2021 21:45:06 +0000 Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.app_directories.Loader: C:\Users\Leroi\Desktop\Ecom_site\Ecomenv\lib\site-packages\django\contrib\admin\templates\pages\index.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\Leroi\Desktop\Ecom_site\Ecomenv\lib\site-packages\django\contrib\auth\templates\pages\index.html (Source does not exist) Traceback Switch to copy-and-paste view C:\Users\Leroi\Desktop\Ecom_site\Ecomenv\lib\site-packages\django\core\handlers\exception.py, line 47, in inner response = get_response(request) -
Why dashboard route is not accessible to me even if I am logged in?
I am using private route in my app to access dashboard. if I am not logged in it worked correctly and redirect me to the sign in page. but even if I am logged in it does not gives access to dashboard. Here is my code. App.js import React from 'react'; import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'; import Home from './containers/Home'; import Login from './containers/Login'; import Dashboard from './containers/Dashboard'; import PrivateRoute from './components/PrivateRoute'; import { Provider } from 'react-redux'; import store from './store'; const App = () => ( <Provider store={store}> <Router> <Layout> <Switch> <Route exact path='/' component={Home} /> <PrivateRoute exact path='/dashboard' component={Dashboard} /> <Route exact path='/login' component={Login} /> </Switch> </Layout> </Router> </Provider> ); export default App; PrivateRoute.js import React from 'react'; import { Route, Redirect } from 'react-router-dom'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; const PrivateRoute = ({ component: Component, auth, ...rest }) => ( <Route {...rest} render={(props) => { if (!auth.isAuthenticated) { return <Redirect to="/login" />; } else { return <Component {...props} />; } }} /> ); const mapStateToProps = (state) => ({ auth: state.auth, }); export default connect(mapStateToProps)(PrivateRoute); And if I am logged in on react redux tool my … -
On Heroku getting error: python: can't open file 'manage.py': [Errno 2] No such file or directory
I try to push a Django website to Heroku and run it in a Docker container. After running "git push heroku master", I get the error "python: can't open file 'manage.py': [Errno 2] No such file or directory". If I try to run "git push heroku master", I get "Everything up-to-date". But running anything involving "manage.py" such as "heroku run python manage.py migrate", will get stuck in the "connecting" phase. The following is the content of the "heroku.yml" file: setup: addons: - plan: heroku-postgres build: docker: web: Dockerfile release: image: web command: - python manage.py collectstatic --noinput run: web: gunicorn bookstore.wsgi Link to the project github What can be the problem? -
Multiple focus selectors to dinamically show QuillJS toolbar, is it possible?
I'm using Django's QuillJS version, and what I'm trying to do is display the toolbar of the selected text area only. Using JS it kinda worked: const parentDiv = Array.from(document.getElementsByClassName("django-quill-widget-container")); const toolbar = Array.from(document.getElementsByClassName("ql-toolbar")); const editor = Array.from(document.getElementsByClassName("ql-editor")); for (let i = 0; i < editor.length; i++) { toolbar[i].style.display = "none"; parentDiv[i].style.borderTop = "1px solid #ccc"; editor[i].addEventListener("focusin", function () { toolbar[i].style.display = ""; parentDiv[i].style.borderTop = ""; }); editor[i].addEventListener("focusout", function () { toolbar[i].style.display = "none"; parentDiv[i].style.borderTop = "1px solid #ccc"; }); } The problem is that clicking the toolbar to utilize its features also counts as focusout. So yeah, it doesn't work. Any idea? -
How to chain a multi-feature search in Django
I have a 3 filter search for a job. One is for the job title/decription/company, one for job category for e.g Banking and one for the location for e.g New York How do I chain the query such that it should render me the appropriate results if I specified any one filter and if I specified all 3 it should perform an AND. I tried doing it with if else, but it is becoming too long. Is there another way? Here is my code: views.py if request.method == "POST": internship_desc = request.POST['internship_desc'] internship_ind = request.POST['internship_industry'] internship_loc = request.POST['internship_location'] results = [] if internship_desc != "" and internship_desc is not None: query_results = Internship.objects.filter( Q(internship_title__icontains=internship_desc) | Q(internship_desc__icontains=internship_desc) | Q(recruiter__company_name__icontains=internship_desc) ) if internship_ind !="" and internship_ind is not None: if internship_desc != "" and internship_desc is not None: query_results = query_results.objects.filter( industry_type__iexact=internship_ind) else: query_results = Internship.objects.filter(industry_type__iexact=internship_ind) if internship_loc !="" and internship_loc is not None: if internship_desc != "" and internship_desc is not None and internship_ind !="" and internship_ind is not None: query_results = query_results.objects.filter( industry_type__iexact=internship_ind) query_results = query_results.objects.filter( recruiter__company_region__iexact=internship_loc) -
Limit the amount of user registration in django
I am newbie in django a I have a question. My system, developed in django, needs to register only the amount of user given in a registration page. How I do to verificate and to limit the amount of registered user? Follow my view: from django.contrib.auth import login, authenticate from django.contrib.auth.decorators import login_required from django.contrib.auth.forms import UserCreationForm from django.shortcuts import render, redirect from django.utils.decorators import method_decorator from apps.criarusuario.forms import SignUpForm from apps.cadastro.models import CadastroCliente # table with amount of users to be registered @login_required def signup(request): form = SignUpForm(request.POST) count = CadastroCliente.qtde_usuarios #count the size of registered user if request.method == 'POST': if form.is_valid(): if (CadastroCliente.qtde_usuarios == count): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) else: if (CadastroCliente.qtde_usuarios == count): form = SignUpForm() return render(request, 'criarusuario/signup.html', {'form': form}) Thank you very much! -
How to keep duplicate query set in django
Hello i am new to django and i am stuck in one small problem def doctor_view_appointment(request): apptdoctor=models.Appointment.objects.all().filter(doctorId=request.user.id,status=True) pat_identity=[] for a in apptdoctor: pat_identity.append(a.patientId) print(pat_identity) pat_data=models.Patient.objects.all().filter(status=True,user_id__in=pat_identity) print(pat_data) appt_doctor=zip(apptdoctor,pat_data) data={ 'appt_doctor': appt_doctor, } return render(request,'doctor_view_appointment.html',context=data) In this code the print result of pat_identity is [5, 20, 5] (they are appointmetn id) and the result of pat_data is <QuerySet [<Patient: User1>, <Patient: User2>]> but i need the result <QuerySet [<Patient: User1>, <Patient: User2>,<Patient: User1>]> what should i do for this output -
Django adding sub headings to a form (Failed lookup for key)
I have a model form with lots of options(I removed most of them for this). I would like to add sub headings to make it look better and so its more readable. From my research I couldn't find a definitive way to do it but the few posts I found said to use crispy forms with a helper and multiple field sets. forms.py from crispy_forms.helper import FormHelper class PostForm(ModelForm): class Meta: model = Post fields = 'title', 'manufacture', 'model', 'aspiration', 'image', 'content', def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['model'].queryset = Models.objects.none() self.helper = FormHelper() self.helper.layout = Layout( Fieldset( 'MY SubHeading ONE' 'title' 'manufacture' ), Fieldset( 'MY SubHeading TWO' 'model' 'aspiration' 'image' 'content' ) ) if 'manufacture' in self.data: try: model_manufacture_id = int(self.data.get('manufacture')) self.fields['model'].queryset = Models.objects.filter(model_manufacture_id=model_manufacture_id)#.order_by('name') except (ValueError, TypeError): pass # invalid input from the client; ignore and fallback to empty City queryset elif self.instance.pk: self.fields['model'].queryset = self.instance.country.city_set#.order_by('name') The if 'manufacture' is for a custom dropdown and is not related along with self.fields['model'].queryset = Models.objects.none() post_form.html <div class="content-section"> <form method="post" enctype="multipart/form-data" id="PostForm" data-models-url="{% url 'ajax' %}" novalidate> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Create Post</legend> {% crispy PostForm PostForm.FormHelper %} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Post</button> </div> </form> </div> … -
Receive email from the another sender not myself
I use my Gmail account to receive an e-mail when a visitor submits the contact form on my website. This is how I have set the parameters in my views.py: email_from = f'{sender_name} <{sender_email>' email_to = ['myemailaddress@gmail.com', ] send_mail(email_subject, '', email_from, email_to, html_message=html_message) And I receive the email and everything is fine — except that the email is coming from myself (the from is myself) not the name and email address of the person submitted the form as I've set in email_from field. How to fix this? -
How to escape the ? character in django using path
I have a title section for one of my models, and in there, when I add a ? in it, and redirect the page with that URL, it adds an extra / in the URL, and leads me to a 404 Not Found. So my question is: How can I escape this character without having to replace it. Also, the extra requirement is, how can I do this with path()? In the urls.py. I am not using regex for this. Please let me know. Thanks! -
Post default to form django
I have a car rental project, in each DetailView of a car, there is form that allows the user to book the car. My problem is i want to send the car model and brand of the car from where the reservation form was used. Here is my code : models.py : class Car(models.Model): trans = (('Manual','Manual'),('Automatic','Automatic')) Fuel = (('Essence','Essence'),('Diesel','Diesel')) brand = models.CharField(max_length=100, blank=False, null=False) model = models.CharField(max_length=100, blank=False, null=False) Transmission = models.CharField(max_length=100, blank=False, null=False, choices=trans, default='Manual') Seats = models.IntegerField(blank=False, null=False, default= 2) fuel = models.CharField(max_length=100, blank=False, null=False, choices=Fuel, default='Essence') features = models.ManyToManyField('Features',blank=False, null=False, related_name='cars') featured = models.BooleanField(default=False) price = models.IntegerField(blank=False, null=False, default= 0) image = models.ImageField(upload_to="media/carimages/", default=None,blank=True,) thumbnail_image = models.ImageField(upload_to="media/thumbnailcarimages/", default=None, blank=True, null=True) def __str__(self): return self.brand + ' ' + self.model class Reservationform(models.Model): pickup = models.CharField(max_length=50, blank=False) pickup_date = models.CharField(max_length=50, blank=False) pickup_time = models.CharField(max_length=50, blank=False) phone = models.CharField(max_length=50, blank=False) treated = models.BooleanField(default=False) b = models.ForeignKey(Car,on_delete=models.CASCADE, default=Car.brand) m = models.ForeignKey(Car,on_delete=models.CASCADE, default=Car.model) forms.py class ReservationForm(forms.ModelForm): class Meta: model = Reservationform fields = ('pickup','pickup_date','pickup_time','b','m','phone',) widgets ={'pickup': forms.TextInput(attrs={'class': "form-control", 'placeholder': "Aéroport Tunis Carthge"}), 'pickup_date': forms.TextInput(attrs={'class': "form-control","id":"book_pick_date" }), 'pickup_time': forms.TextInput(attrs={'class': "form-control", "id":"time_pick"}), 'b': forms.TextInput(), 'm': forms.TextInput(), 'phone': forms.TextInput(attrs={'class': "form-control", "placeholder": "Your contact number"}), } Views.py : class SingleCar(generic.DetailView, FormMixin): model = Car context_object_name … -
Permission denied error while trying to save image inside Django views
I'm trying to save an image that I'm scraping from IMDB(using bs4) but I'm getting this error: [Errno 13] Permission denied: '/media/Django-Unchained.webp' My code was working fine and I could save the images inside the media directory until I changed some other parts of my code which are completely unrelatable to saving image objects or permissions. When I restarted the server I suddenly faced this error. Why would such a thing happen? Thanks in advance for your ideas on solving this. -
Django urls relation
Whenever I add any '/' in front of the action parameter or after the action parameter then a '?' is always included in the URL. What is the relation between '/' and '?'.It doesn't happen with an anchor tag. <form action="about"> <button type="submit"> hello world </button> -
how to remove html encodings from a string in django
I have used the strip_tags function. It removes tags like "<p>, <b>", etc but things like "&nbsp; &ldquo;" and other html encodings remain. How to remove them ?