Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ImportError: Module 'django.contrib' does not contain a 'Advisor' class. ------- why am I getting this error
Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1520.0_x64__qbz5n2kfra8p0\lib\threading.py", line 1016, in _bootstrap_inner self.run() File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1520.0_x64__qbz5n2kfra8p0\lib\threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "C:\Users\mgkco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\mgkco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "C:\Users\mgkco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\mgkco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\core\management\__init__.py", line 398, in execute autoreload.check_errors(django.setup)() File "C:\Users\mgkco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\mgkco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\mgkco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\mgkco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\apps\config.py", line 225, in create raise ImportError(msg) ImportError: Module 'django.contrib' does not contain a 'Advisor' class. -
How to use django-oauth-toolkit to protect a package's API
I'm developing a web API using "django-scim2" package. As a development requirement, bearer token authentication is required when accessing the django-scim2 API via http. The django-scim2 documentation (https://django-scim2.readthedocs.io/en/latest/) says "This app does not implement authorization and authentication. Such tasks are left for other apps such as Django OAuth Toolkit to implement." And as I check the django-oauth-toolkit docs, I can see how to protect it when you create a function or class, https://django-oauth-toolkit.readthedocs.io/en/2.1.0/views/function_based.html https://django-oauth-toolkit.readthedocs.io/en/2.1.0/views/class_based.html but django-scim2 is loaded from config/urls.py as it is (like below), so I have nothing to do and I don't know how to implement it. [config/urls.py] urlpatterns = [ path('admin/', admin.site.urls), path('scim/v2/', include('django_scim.urls', namespace='scim')), ... I would be grateful if you could give me some good advice. -
How to implement this function?
I have model Contact class Contact(models.Model): name = models.CharField(max_length=255) phone = models.CharField(max_length=255) appearance = models.PositiveIntegerField(default=0) def get_appear(self): self.appearance += 1 where appearance is how match I'm browsing this endpoint my views.py is : class ContactView(generics.RetrieveAPIView): queryset = Contact.objects.all() serializer_class = ContactIdSerializer def retrieve(self, request, *args, **kwargs): instance = self.get_object() instance.get_appear() serializer = self.get_serializer(instance) return Response(serializer.data) serializers.py: class ContactIdSerializer(serializers.ModelSerializer): class Meta: model = Contact fields = ['id', 'name', 'phone', 'address', 'appearance'] Problem is when I go to my id : http://127.0.0.1:8000/api/v1/contacts/3/ every time appearance should increase by 1 , but this value always equals 1 and value of appearance in db always equals 0 -
Django/react Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response
I am building a website using django as purely a server and React. I am getting the error Access to XMLHttpRequest at 'http://localhost:8000/dividends/current_yield/hd' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response. so far i've tried Redirect is not allowed for a preflight request and "No 'Access-Control-Allow-Origin' header is present on the requested resource" in django I added corsheaders to my installed apps in django, and still no luck my app.js looks like import React from 'react'; import SearchBar from './SearchBar'; import axios from 'axios'; class App extends React.Component { onSearchSubmit(term) { axios.get('http://localhost:8000/dividends/current_yield/hd', { // params: {query: term}, headers: { // Authorization: 'Client-ID *YOUR KEY HERE*' // "Access-Control-Allow-Origin": "*", } }).then(response => { console.log(response.data.results); }); } render() { return ( <div className="ui container" style={{marginTop: '10px'}}> <SearchBar onSubmit={this.onSearchSubmit} /> </div> ) } } export default App; my views looks like def current_dividend_yield_view(request, ticker): yahoo_stock_obj = yfinance.Ticker(ticker.upper()) price = get_current_price(yahoo_stock_obj) dividends = get_all_dividends(yahoo_stock_obj) current_yield = get_current_dividend_yield(price, dividends) current_yield_object = {'current_yield': current_yield} data = json.dumps(current_yield_object) return HttpResponse(data, content_type='application/json') my settings.py ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'dividends_info.apps.DividendsInfoConfig', 'corsheaders', ] MIDDLEWARE = [ … -
How to import parent template except for its overriden content in django templates?
I'm trying to extend two nested blocks from a parent template in a child template. It goes like this : parent.html {% block parentBlock %} <span> Foo </span> {% block rowBlock %} <button ...> Button here </button> <button ...> Another button here </button> {% endblock rowBlock %} <div> Some other content </div> {% endblock parentBlock %} child.html {% extends 'parent.html' %} {% block parentBlock %} {{ block.super }} # --> See note n°1 below {% block rowBlock %} {{ block.super }} <button ...> A third button that extends the 2 others </button> {% endblock rowBlock %} <div> Content that extends parentBlock from parent.html </div> {% endblock parentBlock %} Note n° 1: Problem is that the child's block.super on parentBlock marked as Note 1 will do a super that includes the new rowBlock and appends the new one one more. Result is like this : <span> Foo </span> <button ...> Button here </button> <button ...> Another button here </button> <button ...> A third button that extends the 2 others </button> <button ...> Button here </button> <button ...> Another button here </button> <button ...> A third button that extends the 2 others </button> <div> Some other content </div> <div> Content that extends … -
Production deployable, scalable and managed solution from Heroku
I explored most of the options available in Heroku and none of them has a feasible and managed plan for Django based eCommerce web application. We basically don't want to manage the infrastructure and configurations, but would like to focus on coding and deploy it on a managed solution that is feasible to us. Currently we have the following software stack on a development server and we would like to find a Heroku managed solution, yet scalable and production deployable. Linux OS Postgres Python 3.10 Django latest ( with and without REST APIs) Vue.js Gunicorn Nginx Let's Encrypt or any SSL Redis Celery Github Jenkins CI/CD (the code is automatically deployed on the development server by running a Jenkins job) Integrated API: Stripe, Twilio, Google and etc. Best regards -
Django template forloop values in jquery
I am using Django for a question and answer project. I have a template with multiple answers and, for each answer, I have a "Comment" button to toggle a textarea where I can add a comment to the answer itself. My problem is, I can just toggle the first "comment" button, because jquery gets the first item as unique id. I post some code to be more clear: template {% for answer in answers %} <div class="col-1"> <div style="text-align: center"> <a title="Dai un voto positivo" href="" class="btn btn-lg"><i class="fas fa-arrow-circle-up"></i></a> <br> <span>{{ answer.count_all_the_votes }}</span> <br> <a title="Dai un voto negativo" href="" class="btn btn-lg"><i class="fas fa-arrow-circle-down"></i></a> <br> {% if request.user == question.post_owner %} <a title="Accetta questa risposta come corretta" href="" class="btn btn-lg"><i class="fas fa-check"></i></a> {% endif %} </div> </div> <div class="col-11"> {{ answer.body|safe }} <br> <div class="mt-3"> {% if request.user == answer.answer_owner %} <a href="">Modifica</a> {% endif %} &nbsp;&nbsp;&nbsp; <a href="">Segnala</a> </div> <hr> {% for comment in answer_comments %} {% if comment.answer.id == answer.id %} <small>{{ comment.comment }} - <a href="">{{ comment.commented_by }}</a> {{ comment.created_at }}</small> <hr> {% endif %} {% endfor %} <button class="btn btn-link" id="ans_show_button{{answer.id}}">Commenta</button> <input type="hidden" name="" value="{{answer.id}}"> <div class="col-6"> <form action="{% url 'questions:add_answer_comment' pk=answer.id %}" method="post"> {% … -
What is the difference between timezone.now and db.models.functions.Now?
Can anyone explain the difference between 'django.db.models.functions.Now' and 'django.utils.timezone.now'? For example, am I correct that functions.Now() returns the system time without timezone stamp, and timezone.now() would return UTC timestamp? When I use print(timezone.now()) I get the expected timestamp however when I print(functions.Now()) I get a blank string. Why is this? In what circumstances is it appropriate to use one method over the other? -
circular import error in django rest framework
I have two custom modules in the root project folder: root/setting.py root/utils/custom_exception.py root/custom_authentication.py I am importing from rest_framework import exception_handler, from rest_framework.exceptions import APIException in the custom_exception.py module. When I import CustomExceptionClass from custom_exception.py in custom_authentication.py, I get a cyclical import error: ImportError: cannot import name 'exception_handler' from partially initialized module 'rest_framework.views' (most likely due to a circular import) However when I import the same exception class inside the authenticate method , the error is gone. Does anyone know why I am not able to import globally? -
Django large file uploads to s3 on heroku
For the love of god can we get a solution for uploading large files to Amazon s3 bucket on heroku? I have been through everything on the net and no working solutions or clear documentation. Meanwhile YouTube uploading hour long HD videos!!!! Please only people with experience or success in uploading large 20 minute videos to there app answer. Don’t want people with no experience references other broken answers. By the way my website is www.theraplounge.co/ and we can’t get large file uploaded for nonthing. (Boto3, these s3-direct widgets) you name it. -
Returning a Crispy Form as response to ajax request
i am trying to fill a form with data via ajax request. The is my attempt so far: view.py: def ajaxGetData(request): pnr=int(request.GET.get('pnr',None)) instance=User.objects.get(pnr=pnr) form=User_Form(instance=instance,prefix="Userdata") return HttpResponse(form.as_p()) Ajax Code: $.ajax({ url: '{%url 'ajaxGetData'%}', type: "get", data: { 'pnr': pnr, }, success: function (data) { if (data) { $('#Userdata-Content').html(data); } } }); It does work, but the form is not rendered with crispy-forms. Is there some code like return HttpResponse(form.as_crispy()) That would return a crispy form? PS: I am quite new to Django and developing websites in general. I want to do a website where you can select a user from a list at the side of the page and then edit a whole bunch of data about him. From what i read doing a one-page-solution was the way to go for that. Would be quite thankful if someone can give me a hint if this is the right way to go about it. Greetings! -
Django Rest Framework - One serailizer for API and drf-spectacular
I have a serializer for DRF, and drf-spectacular. My serializer works that i expect but in GUI don't present currectly. So i need to have tho diffrents serializer one for schema and second for endpoint. But i wanna use one, how to fix this ? My serializer: class GetConversionCasesSerializer(serializers.Serializer): conversionId = serializers.SerializerMethodField() cases = serializers.SerializerMethodField() def get_cases(self, obj): serializer = ResultDataSerializer(ResultData.objects.filter(conversion=obj), many=True) data = serializer.data return data def get_conversionId(self, obj): return obj.id Schema serializer: class GetConversionCasesSerializerSchema(serializers.Serializer): conversionId = serializers.IntegerField() cases = serializers.ListSerializer(child=ResultDataSerializer()) Api endpoint: @extend_schema(request=None, responses=GetConversionCasesSerializerSchema()) def get(self, *args, **kwargs): if self.request.version == "v1": conversion_id = self.kwargs.get('conversion_id') instance = Conversion.objects.get(id=conversion_id) serializer = GetConversionCasesSerializer(instance) serializer.data['c1'] = 'test' return Response(serializer.data) else: return Response(status=status.HTTP_400_BAD_REQUEST) When i use to show schema normal selialiser i have: in schema serializer: How to fix first serializer and have one for schema and get method ? -
Как хранить и отображать параметры сайта (то есть какие-то числа, не связанные с работой django, для моих скриптов) через админку?
Можете подсказать где хранить такую информацию (в базе данных через модели django или как-то по-другому) и как сделать переход к ним в админке. Буду очень благодарен. -
Django: How to stop django session from expiring in django?
I have written a logic where a referer would get some point when the person they refered buy a package. Now the problem with this is that when i refer someone and they sign up and also buys a package immediately i the referer gets some point when after sometime maybe a day, if they buys another package i do not get any point again. In this case i feel like a session is timing out or something, but i cannot really tell what the problem here it. this is the code that gives me (or any user that refered someone) some point when the person they refered buy some package views.py profile_id = request.session.get('ref_profile') if profile_id is not None: recommended_by_profile = Profile.objects.get(id=profile_id) print("Profile Id Is" + str(profile_id)) recommended_by_profile.indirect_ref_earning += 250 recommended_by_profile.save() else: print("Profile ID is None and no point where given") THis s my registerRef view that signs-up a user and detects the person who refered them def registerRef(request, *args, **kwargs): profile_id = request.session.get('ref_profile') print('profile_id', profile_id) code = str(kwargs.get('ref_code')) try: profile = Profile.objects.get(code=code) request.session['ref_profile'] = profile.id print('Referer Profile:', profile.id) except: pass print("Session Expiry Date:" + str(request.session.get_expiry_age())) form = UserRegisterForm(request.POST or None) if form.is_valid(): if profile_id is not None: recommended_by_profile … -
geodjango spatial lookup failure Only numeric values of degree units are allowed on geographic DWithin queries
So I'm building Django app which has some stores saved with coordinates in db, all I need to do, when I get user coordinates, I want to search in db for the nearest store, IDk what to do after receiving coordinates eveything raises error tried this hard coded query lookup Shop.objects.filter(location__dwithin = (GEOSGeometry(Point(-95.23592948913574, 38.97127105172941)), D(km=5))) but still getting errors like Only numeric values of degree units are allowed on geographic DWithin queries. the srid if it matters is 4326, idk even know what this is -
TimeoutError [winError10060]
This is my function for sending email, but i am getting time out error. I tried to solve my problem by disabling the proxy settings and also enabling the imap from gmail. None is helping. Plus I think less secure app option is also disabled. Correct me if I am wrong settings.py EMAIL_HOST = 'smtp.gmail.com' EMAIl_HOST = 587 EMAIL_HOST_USER = 'my email' EMAIL_HOST_PASSWORD = '#####' EMAIL_USE_TLS = True view.py def register(request): if request.method =='POST': form = RegistraionForm(request.POST) if form.is_valid(): first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] phone_number = form.cleaned_data['phone_number'] email = form.cleaned_data['email'] password = form.cleaned_data['password'] username = email.split('@')[0] user = Account.objects.create_user(first_name=first_name,last_name=last_name,email=email,username=username, password=password) user.phone_number = phone_number user.save() #user activation current_site = get_current_site(request) mail_subject = 'Please activate your account' message = render_to_string('accounts/account_verification_email.html',{ 'user': user, 'domain': current_site, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': default_token_generator.make_token(user), }) to_email = email send_email = EmailMessage(mail_subject, message, to=[to_email]) send_email.send() messages.success(request, "Registration successful") return redirect('register') else: form = RegistraionForm() context={ 'form':form, } return render(request, 'accounts/register.html',context) -
How can i update quantity in the django cart?
model.py class OrderItem(models.Model): product = models.ForeignKey(Product,on_delete=models.CASCADE) order = models.ForeignKey(Order, on_delete=models.CASCADE) quantity = models.IntegerField() date_added = models.DateTimeField(auto_now_add=True) if request.method == "POST": customer = request.user.customer order ,created = Order.objects.get_or_create(customer=customer,complete=False) id = request.POST.get('id') product = Product.objects.get(id=id) if OrderItem.objects.filter(product=product): orderitem = OrderItem.objects.filter(product=product) orderitem.quantity+=1 order.save() else: orderitem = OrderItem.objects.create(product=product,order=order,quantity=1) products = Product.objects.all() return render(request, "HTML/index.html",{'products':products}) Error QuerySet' object has no attribute 'quantity' I'm trying to a cart if an item exists in this cart, the system should update its quantity, if not then a new item should be created in the cart, how can i do that? -
Repeated syntax errors while guy in tutorial is getting none
I am new to coding, and am following a tutorial on how to make a forum website. I am instructed to enter two lines of code into the VScode terminal, which are: $ git clone https://github.com/SelmiAbderrahim/AutoDjango.git $ python AutoDjango/AutoDjango.py --venv The first one works fine and clones everything into my workspace, but for the second line I keep getting syntax errors. The first one was for line 43, which was: <h1 class="text-5xl">Django + Tailwind = ❤️</h1> So I took out the heart assuming it was that, but then I just got one for line 44 which was: </section> If anybody knows how to fix this, it would be much appreciated as I have spent days on this project and don't want it to end because of this problem. Here is the tutorial video with the timestamp: Tutorial -
How do I pass django variables to javascript in a for statement?
How do I pass django variables to javascript in a for statement I want to pass c.tv.tv_id in a for statement in javascript. I want to pass it to javascript in each for statement, but I don't know how to do it. {% extends 'base.html' %} {%load static%} <link rel="stylesheet" href="{% static 'css\common_movie_tv.css' %}"> {% block content %} <table> <tr> <tr> <th>name</th> <th>created_at</th> <th>comment</th> <th>evaluation</th> </tr> {% for c in object_list %} <tr> <th id = "trendings"></th> <td>{{ c.user.nickname }}</td> <td>{{c.tv.tv_id}}</td> <td>{{ c.created_at }} </td> <td>{{ c.comment }}</td> <td><h2 class = "rate" style="--rating:{{c.stars}}">{{c.stars}}</h2></td> </tr> {% endfor %} </table> <script> const tv_id = {{c.tv.tv_id}} fetch(`https://api.themoviedb.org/3/tv/${tv_id}?api_key=${TMDB_API_KEY}&language=en-US`, { method: "GET", headers: { "Content-Type": "application/json" } ) .then(res => res.json()) .then(data => { var mainDiv = document.createElement("div"); mainDiv.setAttribute("class", "card"); mainDiv.setAttribute("style", "width: 18rem;"); var img = document.createElement("img"); img.setAttribute("src", "https://image.tmdb.org/t/p/w200" + data.poster_path); img.setAttribute("class", "card-img-top"); img.setAttribute("alt", "..."); var body = document.createElement("div"); body.setAttribute("class", "card-body"); var title = document.createElement("h5"); title.setAttribute("class", "card-title"); if (data.name) { title.innerHTML = data.name; } else { title.innerHTML = data.title; } //var text = document.createElement("p"); //text.setAttribute("class", "card-text"); //text.innerHTML = data.results[i].overview; var link = document.createElement("a"); link.setAttribute("href", "/" + "tv" + "/" + data.id + "/"); link.setAttribute("class", "btn btn-primary"); link.innerHTML = "View Details"; body.appendChild(title); //body.appendChild(text); body.appendChild(link); mainDiv.appendChild(img); mainDiv.appendChild(body); … -
Django app deployment on heroku compiled slug size is too large
So i am deploying my django application which consists on a reural network model used for fungus classification. The total files on the repo wheight like 100MB but i keep getting this error: 129 static files copied to '/tmp/build_dcf9fdff/hongOS_project/staticfiles'. remote: remote: -----> Discovering process types remote: Procfile declares types -> web remote: remote: -----> Compressing... remote: ! Compiled slug size: 1.1G is too large (max is 500M). remote: ! See: http://devcenter.heroku.com/articles/slug-size remote: remote: ! Push failed remote: ! remote: ! ## Warning - The same version of this code has already been built: e8bac23bbcb75c7d2773ba8eecf5613182f0a4ac remote: ! remote: ! We have detected that you have triggered a build from source code with version e8bac23bbcb75c7d2773ba8eecf5613182f0a4ac remote: ! at least twice. One common cause of this behavior is attempting to deploy code from a different branch. remote: ! remote: ! If you are developing on a branch and deploying via git you must run: remote: ! remote: ! git push heroku <branchname>:main remote: ! remote: ! This article goes into details on the behavior: remote: ! https://devcenter.heroku.com/articles/duplicate-build-version remote: remote: Verifying deploy... remote: remote: ! Push rejected to hongos-heroku. remote: To https://git.heroku.com/hongos-heroku.git ! [remote rejected] develop-heroku -> main (pre-receive hook declined) error: fallo el … -
icontains unable to search certain words from a field that uses richtext field - Django
I made a search function in my project where a user can enter a query and a number of fields will be searched before sending a response with the data filtered. As usual I am using icontains in the views for making the queries in my model. I copied certain words directly from a field that uses ckeditor to the searchbar to see if it works. What I have noticed is it is unable to match certain that are in bold form. In the image for example if I search the words arbitration agreement no data is returned but as you can see the words exists in the field. This is happeing with all the bold words. Please help me to solve the problem as I am unable to understand as to why this is happeing. Below is the view that deals with the search functionality. Using ckeditor for the field. views.py def search_citation(request): q = request.data.get('q') print(f'{q}') if q is None: q = "" if len(q) > 78 or len(q) < 1: return Response({"message":'not appropriate'}, status=status.HTTP_200_OK) try: judge_name = Civil.objects.filter(judge_name__icontains = q) case_no = Civil.objects.filter(case_no__icontains = q) party_name = Civil.objects.filter(party_name__icontains = q) advocate_petitioner = Civil.objects.filter(advocate_petitioner__icontains = q) advocate_respondent = … -
footer.html is not included when extending the base.html file
In header.html, I have <h1>Header Section</h1> In footer.html, I have <h1>Footer Section</h1> In base.html I have {% include 'header.html'%} {% block content %} {% endblock %} {% include 'footer.html' %} But when I extend the base template, I only get the header and the content of the page which extends the base. The footer section appears as {% include 'footer.html' %} Why is that? -
Django: Models aren't loaded yet
I am trying to create fixtures dynamically. def create_search_options_fixtures(): for group in search_options_groups: try: this_group, created = SearchOptionGroup.objects.get_or_create( name_en = group['name_en'], ) for opt in group['options']: this_option, created = SearchOptions.objects.get_or_create( name_en = opt['name_en'], ) this_group.columns.add(this_option) this_group.save() except Exception as e: print(str(e)) Apparently the record is not yet created when I try to add a M2M relation. Thank you for any suggestions -
Django : get_context_data method from classview not working
I want to make an application that uploads files to an azure blobstorage, with a part dedicated to the history of all uploaded files. I used the post and get method of classview FormView and it works perfectly to upload the files. Now I have to query the database/model to get the history to display it. So I think the best solution is to use the get_context_data method to pass the data to the template. However it doesn't work, no data are transferred and I can't target the problem. Below is my classview and my html. Views.py class DocumentUpload(FormView) : model = TblDocument template_name = 'documents/documents.html' form_class = FilesForm context_object_name = 'object_list' def get_context_data(self, *args, **kwargs): # Call the base implementation first to get a context context = super(DocumentUpload, self).get_context_data(*args, **kwargs) context['object_list'] = TblDocument.objects.all() return context def get(self, request, *args, **kwargs): form = self.form_class() return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST, request.FILES) files_selected = request.FILES.getlist('Filename') # create a list of files if form.is_valid(): for file in files_selected : # DEFINE THE DATA OF THE FILE file = FileDefinitionBeforeUpload(file=file).file_information() # GET THE CONTENT OF THE FILE content = file.read() file_io = BytesIO(content) # THE UPLOAD … -
Django TemplateDoesNotExist. Django doesn't check one of the my apps, when looking for templates
Django can't find needed template from my app. I named directory "app/template/app/template.html", my settings: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] Also I add my app name in INSTALED_APPS. I tried move my template in project's directory and its work! But I just wanna understand, why loader didn't check my app directory