Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django App Not Reflecting the Changes in Files
I have a droplet on Digitalocean that runs Django. Whenever I make any changes on urls.py or views.py, I need to reboot the server in order to apply those changes in production. Is there any alternative method? Like if I delete the content of pycache directory, will it work? I tried touch commands but that didn't work. -
Can i add debit card details to billibg information details on heroku?
I have not credit card and i want to deploy a django app but requires payment method verification and this can done only done by credit card payment method on heroku so what i can do? I trie to add details of my debit card but not works. I think that this works because so many peoples having no any credit card then what those peoples do? -
Creating a test Django environment from the existing production Django project
I've developed a Django project which is in production and used by a small team daily. Now I want to make some changes in UI, since there is no test environment, I tried creating a similar base and home page with different names for testing in production environment but it is throwing error in ajax url resolving, I don't want to create another set of ajax url for testing. Is there any better way to create a test environment to test the UI changes and copy the html and java script alone? (it is a single developer project I use github only when I push any big change) -
increase the waiting time for response from server before returning the server time error with django and kubernetes
I am using Kubernetes and Google Cloud to host my web application and was looking for a way to increase the time for waiting for the server response before returning the error Internal server error Sorry, there seems to be an error. Please try again soon. I tried to search for the Kubernetes objects but no result thank you -
Django single choice field with choice of programming language category and quantity of possible answers
I would like to create a single choice quiz in Django. The question creator must: the possibility to add as many answers' fields as possible with a plus + or arrows up-down be capable of marking solely one answer as correct. be capable of choosing of predestined programming language category like here in text question. [![Singlequestion][1]][1] Here is my code: models.py # models.py from django.db import models class Category(models.Model): language_name = models.CharField(max_length=100, unique=True, default='') def __str__(self): return self.language_name class SingleChoiceQuestion(models.Model): question_text = models.CharField(max_length=255) category = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self): return self.question_text class SingleChoiceOption(models.Model): question = models.ForeignKey(SingleChoiceQuestion, on_delete=models.CASCADE) option_text = models.CharField(max_length=255) is_correct = models.BooleanField(default=False) def __str__(self): return self.option_text forms.py # forms.py from django import forms from .models import SingleChoiceQuestion, SingleChoiceOption class SingleChoiceQuestionForm(forms.ModelForm): class Meta: model = SingleChoiceQuestion fields = ['question_text', 'category'] options_count = forms.IntegerField(min_value=2, max_value=4, label="Number of Options Anzahl der Optionen") def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) options_count = self.initial.get('options_count', 2) for i in range(options_count): self.fields[f'option_{i + 1}'] = forms.CharField(max_length=255, required=True) self.fields['correct_option'] = forms.ChoiceField( choices=[(f'option_{i + 1}', f'Option {i + 1}') for i in range(options_count)], widget=forms.RadioSelect, required=True, label="Correct Option Richtige Option" ) views.py # views.py from django.shortcuts import render, redirect from django.views import View from .forms import SingleChoiceQuestionForm class CreateSingleChoiceQuestionView(View): template_name … -
Dynamically creating models in django to be used in a unit test
I am attempting to create a test model in a unit test so that I can test associated behavior. Django documentation and related questions here on SO, both indicate that I should use the isolate_apps utility function, that in theory should register a temporary app which holds my test model. Note that I'm on django v1.11. My test looks like this: from django.test.utils import isolate_apps from django.db import models from django.test import TestCase class MyTest(TestCase): @isolate_apps("app_label") def test_the_model(self): class TestModel(models.Model): field = models.CharField(max_length=10) I'm not even running any assertions because it fails before. Error stack trace /usr/local/lib/python3.7/site-packages/django/test/utils.py:381: in inner with self as context: /usr/local/lib/python3.7/site-packages/django/test/utils.py:353: in __enter__ return self.enable() /usr/local/lib/python3.7/site-packages/django/test/utils.py:878: in enable apps = Apps(self.installed_apps) /usr/local/lib/python3.7/site-packages/django/apps/registry.py:56: in __init__ self.populate(installed_apps) /usr/local/lib/python3.7/site-packages/django/apps/registry.py:85: in populate app_config = AppConfig.create(entry) /usr/local/lib/python3.7/site-packages/django/apps/config.py:94: in create module = import_module(entry) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ … -
from django.template import Template will this command into conda give me a folder inside my main one?
from django.template import Template in my class we are trying to create a folder inside our main folder, but I have no idea how to it. will from django.template import Template give a new folder inside my main one? btw, we are using VS code and Anaconda as the powershell. I am hoping someone can help me understand how to create a folder using django through conda -
Only default home page is working when deploying in PythonAnywhere
error message I deployed my Django webapp in PythonAnywhere. Despite following every step, my webapp is displaying only 1 page. As soon as i click on a link to go to other pages, the webapp stops working and gives an error message saying something went wrong with no proper details. But everything works fine when using it on localhost. These are the nav and urls.py files: nav.html: <div class="topbar"> <header> <li><a id="TOP_name" href="home"><img src="{%static 'prasant1.png' %}" height="50"></a></li> </header> <ul> <li><a id="right" href="contact">CONTACT</a></li> <li><a id="right" href="resume">RESUME</a></li> <li><a id="right" href="work">WORK</a></li> <li><a id="right" href="experience">EXPERIENCE</a></li> <li><a id="right" href="education">EDUCATION</a></li> </ul> </div> project/urls.py urlpatterns = [ path('', views.home), path('home', views.home), path('work', views.work), path('resume', views.Resume), path('education', views.education), path('contact',views.contact), path('experience',views.experience), ] urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('home.urls')), ] I tried changing the "home" link with "work" link but that makes the condition worse as it doesn't even load 1 page now. So from my point of view the problem might be with other html files. Please help me out on how to solve this is PythonAnywhere. -
Update and save model data from a view function in Django
I am looking to create an automation strategy for data validation via the Django Admin. My Idea is to save transaction data in my Admin panel then later query the database for validation. I am still on my training wheels with Django, and any help will be much appreciated. the initial event will be triggered through to this JS function function save_this_data_to_models(event) { user_name = "user name"; data = "I need this data auto saved to my models in admin via this called view fucntion"; window.fetch(`/save_this_data_to_models?data=${data}&name=${user_name}`); event.preventDefault(); } the JS function calls and passes user data to this Python View function def save_this_data_to_models(request): # the data i need saved to my models data = request.GET.get('data', 'default') user_name = request.GET.get('name', 'default') print('') print('==========') print(user_name) print('==========') print('') print('=================================================================================') print(data) print('=================================================================================') print('') return HttpResponse(request) the prints are for my sanity. this is my modles.py file where i want to save this data automatically in my Admin site from django.db import models class Name(models.Model): # defining the fields i want to be saved to the database User_name = models.CharField(max_length=50) def __str__(self): return self.User_name class Data(models.Model): # defining the fields i want to be saved to the database Data = models.CharField(max_length=400) def __str__(self): return self.Data … -
Django - Unable to get a ClearableInputField to have the "multiple: True" to work
I am trying to allow my users to select multiple files when uploading file(s). I am trying to allow the field on the forms.py file to have this functionality with the "multiple" property. I have seen other examples found online, but it does not work for me. forms.py", line 168, in Meta "image": ClearableFileInput(attrs={"multiple": True}), File "/x/x/x/lib64/python3.6/site-packages/django/forms/widgets.py", line 393, in __init__ % self.__class__.__qualname__ ValueError: ClearableFileInput doesn't support uploading multiple files. pip list Package Version ----------------- ------- asgiref 3.4.1 Django 3.2.21 django-auth-ldap 4.0.0 django-filter 21.1 lxml 4.9.3 mysqlclient 2.1.1 Pillow 8.4.0 pip 21.3.1 pyasn1 0.5.0 pyasn1-modules 0.3.0 python-docx 0.8.11 python-ldap 3.4.3 pytz 2023.3 setuptools 39.2.0 sqlparse 0.4.4 typing_extensions 4.1.1 forms.py from django.forms import ModelForm, Textarea, Select, ClearableFileInput class UploadImageForm(ModelForm): class Meta: model = Images fields = [ "image", "description" ] labels = { "image": ("Image"), "description": ("Description") } widgets = { "image": ClearableFileInput(attrs={"multiple": True}), } models.py class Images(models.Model): id = models.BigAutoField(primary_key=True) image = models.ImageField(upload_to='images/', null=True) test_part_id = models.ForeignKey('TestParts', on_delete=models.PROTECT, blank=True, null=True) description = models.CharField(max_length=512, blank=True) class Meta: db_table = 'images' def __str__(self): return f"{self.image}" views.py def testing(request): if request.method == "POST" and "fileForm" in request.POST: imageForm = UploadImageForm(request.POST, request.FILES) if imageForm.is_valid(): for image in request.FILES.getlist('files'): new_image = Images(image=image) new_image.save() return redirect(fa_details, … -
Django Quiz- multiple question, saving to database failed, failed to convey programming language category field onto the screen
I neither can get the multi question form saved nor can I save the data in the database. The is one field for programming language category lacking. I would like to get the questions assigned to proper category like Python, JS, PHP etc. No Category field and no possibility to save in database. Here you can see the category field - it gets saved in the database Here is my code: #HTML {% extends 'dependencies.html' %} {% block content %} <div class="jumbotron container row"> <div class="col-md-6"> <h1>Add Question</h1> <div class="card card-body"> <form action="" method="POST"> {% csrf_token %} {{ form.question.label_tag }} {{ form.question }} <br> <label for="id_ans_count">Number of Answers Anzahl der Antworten:</label> {{ form.ans_count }} <br> <div id="answers-container"> {% for i in form.visible_fields %} {% if 'answer_' in i.name or 'is_correct_' in i.name %} {{ i.label_tag }} {{ i }} <br> {% endif %} {% endfor %} </div> <input type="submit" name="Submit"> </form> </div> </div> </div> <script> // JavaScript, um dynamisch Antworten hinzuzufügen const ansCountInput = document.getElementById("id_ans_count"); const answersContainer = document.getElementById("answers-container"); ansCountInput.addEventListener("change", function () { const ansCount = parseInt(this.value); answersContainer.innerHTML = ""; // Leeren Sie das Container-Div for (let i = 0; i < ansCount; i++) { const answerField = document.createElement("div"); answerField.innerHTML … -
Django Rest Framework- retrieving listing updating deleting
I have this class for create and update cuorse content How I convert or wite API view form this view class ContentCreateUpdateView(TemplateResponseMixin, View): module = None model = None obj = None template_name = 'courses/manage/content/form.html' def get_model(self, model_name): if model_name in ['text', 'video', 'image', 'file']: return apps.get_model(app_label='courses', model_name=model_name) return None def get_form(self, model, *args, **kwargs): Form = modelform_factory(model, exclude=['owner', 'order', 'created', 'updated']) return Form(*args, **kwargs) def dispatch(self, request, module_id, model_name, id=None): self.module = get_object_or_404(Module, id=module_id, course__owner=request.user) self.model = self.get_model(model_name) if id: self.obj = get_object_or_404(self.model, id=id, owner=request.user) return super().dispatch(request, module_id, model_name, id) def get(self, request, module_id, model_name, id=None): form = self.get_form(self.model, instance=self.obj) return self.render_to_response({'form': form, 'object': self.obj}) def post(self, request, module_id, model_name, id=None): form = self.get_form(self.model, instance=self.obj, data=request.POST, files=request.FILES) if form.is_valid(): obj = form.save(commit=False) obj.owner = request.user obj.save() if not id: # new content Content.objects.create(module=self.module, item=obj) return redirect('module_content_list', self.module.id) return self.render_to_response({'form': form, 'object': self.obj}) I want wite API code using django restframework I build LMS using Django I backed and react in front-end The problem is how write API if I have hard code like this -
Django backend cannot access Cookies
Hey I'm trying to access my jwt token in my cookies to do authorization in my backend. But when trying to access my cookie from the request I receive an empty dict. The cookie is created like this in my frontend. cookies.set("jwttoken", result.data.token, { path: "/", maxAge: 3600}); this is done using the universal-cookie npm package. In my backend I try to access my cookies like this. jwt = request.COOKIES.get("jwttoken") But receive None when trying to print the token. This is everything CORS related in my settings.py CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CSRF_USE_SESSIONS = False SESSION_COOKIE_SECURE = False CSRF_COOKIE_SECURE = False CSRF_COOKIE_SAMESITE = None SESSION_COOKIE_SAMESITE = None CORS_ALLOWED_ORIGINS = [ "http://127.0.0.1:8000", "https://********-*******.******.com", "https://www.******.com" ] Thanks for all the help -
Django - How to extend a template from within an app correctly
I am working on a Udemy class to get back into Django development, and this class has me doing the templates folder differently than I am used to. This is the current directory for my file structure showing where my templates are located: VS Code Directory Structure and extended template I can't embed yet, so this is the best I can do. Please ignore the ARCHIVES directory, that is just there while I test things out. I am trying to extend store.html off of base.html, but to test things, I am trying to extend from 'test.html' which you can see in the image. Historically, I have always added the templates directory to the top level, but this class has them on the app level. My problem here is that I can't get the store.html to show up. The test.html (base) is showing up fine, but I can't extend off of it and I have tried messing with the {% extends './test.html' %) as far as using 'store/test.html', 'test.html', and '../test.html'. I know this latter one goes back another directory level, but I just wanted to state that I have been trying to change where it looks. A few things: my … -
Virtual environment not activating in visual studio code windows 11
i am getting this error & : File C:\Users\mudit\vscode\python django projects\dev\venv\Scripts\Activate.ps1 cannot be loaded. The file C:\Users\mudit\vscode\python django projects\dev\venv\Scripts\Activate.ps1 is not digitally signed. You cannot run this script on the current system. For more information about running scripts and setting execution policy, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170. At line:1 char:3 & "c:/Users/mudit/vscode/python django projects/dev/venv/Scripts/Acti ... + CategoryInfo : SecurityError: (:) [], PSSecurityException + FullyQualifiedErrorId : UnauthorizedAccess check out this screenshot for better understanding. -
Is there a way to test if all my `reverse()` calls in Django Views resolve?
I use reverse('route_name') in my views for redirection. If I do any refactoring of the urls, be it renaming the routes, moving some routes to other urls.py file or something similar, I will have to update all the route names in all my views. It is very easy to miss some of the files. It seems trivial to simply grep all the reverse() calls from all the views and simply check if they resolve. The same thing with template files. It seems trivial to grep all the template names and check if they exist, or have they been moved or renamed and not updated in the views. I'm wondering if there is already some kind of package that does this. I've tried googling, but anything I search for focuses on writing specific tests. I'm wondering if there exists something that will help me avoid writing specific tests for each view. For example: Let's say I have a route: path('/payments/cart', CartView.as_view(), name='payments-cart') If I decide to move the url definition into the payments app, the new name will be cart and the reversing of the url in the view will be done as reverse('payments:cart'). If any of my views still reference … -
Accessing images using URL from a server with restrictions in React
I'm working on a web application using React for the front end and Django for the backend, where I need to display images from a server that has access restrictions in place. These restrictions prevent direct access to the images via a URL(tho I still can access it if I just paste the link into a browser), which is causing issues when trying to display them on my website. Here is an example of the image URL: 'https://mangatx.com/wp-content/uploads/2022/01/Level-1-Player-Manga-Online-193x278.jpg' I've tried using the standard <img> HTML tag to display these images, but I'm encountering a 403 error, indicating that I don't have permission to access the images directly. I have also used a Django templating engine to try to display an image, and it worked somehow, but when I switched to react, it didn't work. Is there a recommended approach or workaround for displaying these images in my web application, considering the server restrictions? I do not want to download the images before displaying them as it will go against the purpose of the application. I also don't want to use a proxy server, as my application has a lot of images and it will be too inefficient. Any ideas would … -
Pytest-django unexpected models test behaviour
I have my Django project with pytest and pytest-django package. I have test_models.py file with my test: import pytest from django.contrib.auth import get_user_model # # Get User model User = get_user_model() # Create your tests here. @pytest.mark.django_db def test_create_user(): assert User.objects.create() I use my custom User model with required fields username, email, password, first_name, last_name. But when I try to create User instance without these fields my tests are passing successfully. Why does my User model have such a behaviour? My models.py: from django.db import models from django.contrib.auth.models import AbstractUser from api.managers import CustomUserManager # Create your models here. # Abstract model TimeStampedModel class TimeStampedModel(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: # abstract = True to enable models inherit from TimeStampedModel abstract = True # Custom User model class User(AbstractUser, TimeStampedModel): # Make these fields not to be null email = models.EmailField(unique=True, null=False, blank=False) first_name = models.CharField(max_length=30, blank=False, null=False) last_name = models.CharField(max_length=30, blank=False, null=False) # Assing base user manager for admin panel objects = CustomUserManager() I expect that test gives me the error that I can't create a User instance. I've tried to import directly User model from api.models. -
Static files are not loading in Django project in replit
I am working on a project using Python-Django in repl.it. When I set DEBUG=True in settings.py, the static files are loading fine but when DEBUG is set to False (DEBUG=False), the static files are not loading and getting 404 error on the console. Please help me in fixing it. I am assuming there should be a place where we need to define static location like we do in nginx config file as follows location /static/ { alias /var/www/example.com/current/static/; gzip_static on; expires max; add_header Cache-Control public; } Here is my settings.py file: """ Django settings for django_project project. Generated by 'django-admin startproject' using Django 3.2.13. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.getenv('SECRET_KEY') if SECRET_KEY is None: print( "Please setup a SECRET_KEY in the Secrets (Environment variables) tab. See README.md for more." ) exit(1) # SECURITY WARNING: don't run with debug turned on in … -
NoReverseMatch at / Django e python
I'm trying to creat a new app but I am getting this error 'NoReverseMatch at' This is my project urls.py urlpatterns = [ path('', include('app_infos_gerais.urls') ) ] settings.py INSTALLED_APPS = [ 'app_infos_gerais', ] My app urls.py from django.urls import path from . import views app_name= 'app_infos_gerais' urlpatterns = [ path('infosgerais/', views.infos_gerais, name="resultado_infos_gerais") My app view.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def infos_gerais(request): return HttpResponse('Olá, teste!') My app html {% extends 'modelo-tratore.html' %} {% block pagetitle %} Dados gerais {% endblock %} {% load static %} {% block conteudo %} {% if request.user.is_authenticated %} <div> <p>Teste</p> </div> And the file where Im trying to call the url <li class="p-3"> <a href="{% url 'resultado_infos_geraisß' %}">Infos gerais</a> </li> What am I doing wrong? I tried everything I found but nothing worked. -
Не могу выставить правильную временную зону в Django [closed]
Я в самом начале изучения Django. Извиняюсь за глупы вопрос) Создал проект в самом начале не указал временную зону, добавил записи в базу данных и провел миграции. Как правильно исправить временную зону? Чтоб ранее добавленные записи выводились в нужной временной зоне. Пробовал изменить в settings настройку "UTC" на "UTC+6" выдает ошибку. Спасибо. TIME_ZONE = 'UTC' -
celery task received but not executed (eventlet, django)
I faced a problem that when running celery with eventlet and remote database (Redis) tasks come but are not executed, before that I used gevent and it worked correctly with both local and remote databases, but it does not have the ability to stop tasks, I tried all the options I found on the Internet and on StackOverflow, but none of them helped. I add my settings there Django settings: # settings.py CELERY_BROKER_URL = REDIS_CONN_URL + "0" CELERY_RESULT_BACKEND = REDIS_CONN_URL + "0" CELERY_WORKER_CONCURRENCY = 1000 Celery settings: import os import ssl from celery import Celery from celery.schedules import crontab os.environ.setdefault("DJANGO_SETTINGS_MODULE", "SailAPI.settings") celery_app = Celery( "SailAPI", broker_use_ssl={"ssl_cert_reqs": ssl.CERT_REQUIRED, "ssl_ca_certs": ssl.get_default_verify_paths().cafile}, redis_backend_use_ssl={"ssl_cert_reqs": ssl.CERT_REQUIRED, "ssl_ca_certs": ssl.get_default_verify_paths().cafile}, ) celery_app.config_from_object("django.conf:settings", namespace="CELERY") celery_app.conf.update( enable_utc=True, timezone="UTC", worker_concurrency=8, worker_pool="eventlet", ) celery_app.conf.beat_schedule = { "update_user_status": { "task": "user_app.tasks.update_user_status", "schedule": crontab(hour="4", minute="0", day_of_week="sat"), } } celery_app.autodiscover_tasks() The problem is that tasks that are added to the queue are not executed. I use an eventlet (because it has the ability to stop tasks that are running) and when I run it locally (Windows) with a local database (redis) it works fine, accepts tasks, executes them, stops at the command, but when I threw the code on the server (Linux) and ran … -
text are going out of the container and it's appearing in just one line and goes out of the page
I am trying to add some texts to my project-details section using rich text uploading field in Django admin. There it should be in a paragraph as I have added them in my Django admin project description but it's showing a line and also it goes out of the container and, but it gives space on the left side of the container but not in the right side of container and it goes out of page 😥 here is my project-details.html page: {% extends "base.html" %} {% load static %} {% static "images" as baseUrl %} {% block title %}{{projectdetails.title}}{% endblock %} <!--header block --> {% block header %} <!-- Slider Start --> <section class="section about"> <div class="container">{{projectdetails.desc|safe}}</div> </section> <!--slider ends --> <!-- footer Start --> {% block footer %} <!--Essential Scripts --> {% block Scripts %} {% endblock %} {% endblock %} {% endblock %} here is my project.html page: {% extends "base.html" %} {% load static %} {% static "images" as baseUrl %} {% block title %}Project{% endblock %} <!--header block --> {% block header %} <!-- slider starts --> </div> <div class="typing"> <p class="type4"></p> </div> <!-- section portfolio start --> <section class="section box"> <div class="container"> <div class="row … -
Why is my form calling the wrong Django view?
The flow of my app is as follows: A file is submitted on the transcribe.html page first which then redirects to the transcibe-complete.html page where the user can click to beginning transcription. Why is the 'transcribeSubmit' view being called instead of the 'initiate_transcription' view when the user clicks the 'click to transcribe' button on the 'initiate_transcription' page? Each page has their own JS file to ensure that forms are submitted separately. html: (transcribe.html): <form method="post" action="{% url 'transcribeSubmit' %}" enctype="multipart/form-data" > {% csrf_token %} <label for="transcribe-file" class="transcribe-file-label">Choose audio/video file</label> <input id="transcribe-file" name="file" type="file" accept="audio/*, video/*" hidden> <button class="upload" id="transcribe-submit" type="submit" >Submit</button> </form> (transcribe-complete): <form method="post" action="{% url 'initiate_transcription' %}" enctype="multipart/form-data"> {% csrf_token %} <label for="output-lang--select-summary"></label> <select class="output-lang-select" id="output-lang--select-summary" name="audio_language"> <option value="detect">Detect language</option> <option value="zh">Chinese</option> <option value="en">English</option> <option value="es">Spanish</option> <option value="de">German</option> <option value="jp">Japanese</option> <option value="ko">Korean</option> <option value="ru">Russian</option> <option value="pt">Portugese</option> </select> </div> <div class="transcribe-output"> <button id="transcribe-button" type="submit">Click to Transcribe</button> </div> </form> JS: const form = document.querySelector('form'); form.addeventlistener('submit', function (event) { event.preventdefault(); const formdata = new formdata(form); const xhr = new xmlhttprequest(); xhr.open('post', form.getattribute('action'), true); xhr.onreadystatechange = function () { console.log("ready state: ", xhr.readystate); console.log("status: ", xhr.status); } xhr.responsetype = 'blob'; xhr.send(formdata); }); views.py: @csrf_protect def transcribeSubmit(request): if request.method == 'POST': form = … -
Render the Django REST Framework uploading system with an HTML script
I have developed a simple file-upload system using Django REST Framework using this tutorial How to upload files to AWS S3 with Django. Basically the system allows user to upload files to an AWS S3 bucket. This is what the users currently see: This is the following django project structure: DROPBOXER-MASTER | |--- dropboxer | |--- settings.py |--- urls.py |--- wsgi.py |--- uploader | |--- views.py |--- urls.py |--- serializers.py |--- models.py |--- apps.py |--- templates |--- index.html |--- manage.py |--- requirements.txt This is the dropboxer/urls.py: from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include # new urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('rest_framework.urls')), # new path('', include('uploader.urls')), # new ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) This is the dropboxer/settings.py: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '*****************************************' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ["*"] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', …