Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Style CheckboxSelectMultiple form field. Django
I have a form which has one checkboxselectmultiple field: class CreateRecipeForm(forms.ModelForm): class Meta: model = Recipe fields = ('name', 'image', 'description', 'cooking_time', 'tags') widgets = { ... 'tags': forms.CheckboxSelectMultiple(), ... } I can iterate through field's options like: {% for option in form.tags %} {{ option.tag }} {{ option.choice_label }} {% endfor %} How would I render {{ option.tag }} as an input field? i.e: <input type="checkbox"...> Thanks. -
Django: What is the simplest way to shorten the application url?
I have a Django application that has a long name "encyclopedia". I would like the url for the application that appears on the address bar to be something shorter like "http://127.0.0.1:8000/ency" instead of "http://127.0.0.1:8000/encyclopedia" . What is the simplest way to accomplish this without compromising the functionality of the application? I suspect its something very simple like modifying ROOT_URLCONF in settings.py. There is a general lack of examples that illustrate how to in the documents. -
Django admin different list_display based on what filter is selected?
I want to display based on a Boolean field filter different list_displays for my model in Django admin. For example, if the boolean field is false I should list_display=('name', 'age') but if is true I should display list_display=('name', 'school', 'grades') assuming that my Model have all those fields. -
Why is request.user is anonymous in Django RedirectView?
There are a lot of questions similar to this one, but none quite capture the situation I am in. I am coding a Django/ React app and I have integrated with Spotify. Currently, on the Django side of things I have the user getting redirected back to their profile page after connecting to Spotify. This is done hardcoding the URL with the http response redirect: class SpotifyCallbackView(RedirectView): def handle_callback(self, request): print(self.request.META) if request.GET.get("refresh_token", False): refresh_token = request.GET["refresh_token"] code = request.GET["code"] if request.GET.get("refresh_token", False): response = requests.post( "https://accounts.spotify.com/api/token", data={ "grant_type": "refresh_token", "refresh_token": refresh_token, }, headers=AUTH_HEADER, ) return response.json() else: response = requests.post( "https://accounts.spotify.com/api/token", data={ "grant_type": "authorization_code", "code": code, "redirect_uri": request.build_absolute_uri("callback"), }, headers=AUTH_HEADER, ) return response.json() def get(self, request, *args, **kwargs): auth_items = self.handle_callback(request) access_token = auth_items["access_token"] if "refresh_token" in auth_items.keys(): refresh_token = auth_items["refresh_token"] else: refresh_token = "" if refresh_token != "": return HttpResponseRedirect('http://localhost:3000/users/1/' + access_token + '/' + refresh_token) else: return HttpResponse(access_token) Obviously, the user's ID is not always going to be "1" so I want to be able to grab that ID from somewhere, and after some searching I saw that I can grab that info from self.request.user, except I can't. It's anonymous. Why is this the case? I am … -
add to cart without login or register
models.py class orderbook(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) Book = models.ForeignKey(book, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) def __str__(self): return f"{self.quantity} of {self.Book.book_nm}" def get_total_book_price(self): return self.quantity * self.Book.book_price class Order(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) books = models.ManyToManyField(orderbook) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) def __str__(self): return self.user.username def get_total(self): total = 0 for order_book in self.books.all(): total += order_book.get_total_book_price() return total views.py def add_to_cart(request, slug): Book = get_object_or_404(book, slug=slug) order_book, created = orderbook.objects.get_or_create( Book=Book, user=request.user, ordered=False) order_qs = Order.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] if order.books.filter(Book__slug=Book.slug).exists(): order_book.quantity += 1 order_book.save() messages.info( request, " Cart updated") else: order.books.add(order_book) messages.info(request, "Added to your cart.") else: ordered_date = timezone.now() order = Order.objects.create( user=request.user, ordered_date=ordered_date) order.books.add(order_book) messages.info(request, "Added to your cart.") return redirect(request.META['HTTP_REFERER']) I want to make add to cart work without login or register and whenever user register or login items will be reflected in the user's cart. It may be using a session or overriding the user model. -
How to handle asynchronous requests to an API that are dependent on one another?
Background See diagram below for a hypothetical Django-rest-framework backend structure where A, B, and C are Django models in models.py which have corresponding endpoints for retrieving their data in urls.py /A, /B, and /C for example. Each one of these models contains an isDirty flag along with their own value. Model C is dependent on Model B and Model B is dependent on A. Example: One example could be: A: Timeseries data block [n x m] B: Common start date C: Calculation model. In this example, in order to calculate C, it must retrieve the common start date among all columns of data, which relies on the actual timeseries selected in A. Problem I have a frontend of a web application that is sending asynchronous requests to attempt to display both B and C on a particular screen. Assume that all three models are isDirty=True at this point in time on screen enter. Is there an industry standard approach to handling asynchronous requests to an API that are dependent on one another? If not, how do people typically handle problems such as this regarding state? Solution Attempt: I have attempted to use an atomic transaction on the model tables themselves … -
How to access django server from different network?
I have my Django application running with python manage.py runserver 0.0.0.0:8000 It is accessible within same network in every device with <your LAN ipv4 address>:8000 However. I want to access this outside my network with <your public address>:8000 What is the way to do this? Django app is running on windows 10. I have already written ALLOWED HOSTS : ["*"] Maybe there's some issue with DNS or firewall. 0.0.0.0 should let me access with <your public address>:8000 but it is not giving access. Please help.. -
How to refer to child class in Django REST framework mixin?
In Django Rest Framework, I'm trying to write a mixin for the following two methods in view sets: class OrderViewSet(viewsets.ModelViewSet): # ... def get_object(self): pk = self.kwargs.get('pk') if pk == 'me': user = self.request.user return get_object_or_404(Order, user=user.pk) return super(OrderViewSet, self).get_object() def get_queryset(self): user = self.request.user return Agent.objects.filter(user=user) This seems straight forward except for the super(OrderViewSet, self) because I'll need to somehow refer to different viewset classes in my mixin class before they're declared. Any tips? -
url not showing because of middleware file
Im trying to access my index view but i' m automatically redirected to show_login view , i think that the problem comes from my custom middleware file here is the main view: def indexmain(request): return render(request, "main_template/index.html") Urls : path('admin/', admin.site.urls), path('accounts/',include('django.contrib.auth.urls')), path('', views.ShowLoginPage, name="show_login"), path('indexmain', views.indexmain,name="index"), path('get_user_details', views.GetUserDetails), path('logout_user', views.logout_user,name="logout"), path('doLogin',views.doLogin,name="do_login"), here is my custom Middleware file: from django.http import HttpResponseRedirect from django.urls import reverse from django.utils.deprecation import MiddlewareMixin class LoginCheckMiddleWare(MiddlewareMixin): def process_view(self,request,view_func,view_args,view_kwargs): modulename=view_func.__module__ print(modulename) user=request.user if user.is_authenticated: if user.user_type == "1": if modulename == "gestion.HodViews": pass elif modulename == "gestion.views" or modulename == "django.views.static": pass elif modulename == "django.contrib.auth.views" or modulename =="django.contrib.admin.sites": pass else: return HttpResponseRedirect(reverse("admin_home")) elif user.user_type == "2": if modulename == "gestion.StaffViews" or modulename == "gestion.EditResultVIewClass": pass elif modulename == "student_management_app.views" or modulename == "django.views.static": pass else: return HttpResponseRedirect(reverse("staff_home")) else: return HttpResponseRedirect(reverse("show_login")) else: if request.path == reverse("index") or request.path == reverse("show_login") or request.path == reverse("do_login") or modulename == "django.contrib.auth.views" or modulename =="django.contrib.admin.sites" : pass else: return HttpResponseRedirect(reverse("show_login")) -
Unable to set session variable across subdomains with Django
I have a site that uses multiple subdomains to separate some apps into their own little "mini-sites". For example, I have "mydomain.io" which is a kind of landing page, "5e.mydomain.io" and "pf2e.mydomain.io" which distinguish between different RPG systems, as well as "wb.mydomain.io" which is for the worldbuilding app. They all use the same database and code, but have different templates and some different CSS. I've got it all working with django-hosts. I also managed to get it to keep a user logged in across the various subdomains. However, I'm still having trouble saving a session variable if I'm on any of the subdomains rather than just the main domain. For example, I have some JS that will send an AJAX request to a view which will set "request.session['nav']" to either pinned or unpinned (to let the user pin/collapse the main nav menu). This is only working on the main domain, though. Here's my code. settings.py - you can see I did set the cookie domain to ".mydomain.io" and that solved the login issue MIDDLEWARE = [ "django_hosts.middleware.HostsRequestMiddleware", "corsheaders.middleware.CorsMiddleware", "django.middleware.security.SecurityMiddleware", "whitenoise.middleware.WhiteNoiseMiddleware", "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", "admin_reorder.middleware.ModelAdminReorder", "django_hosts.middleware.HostsResponseMiddleware", ] ROOT_URLCONF = "config.urls" ROOT_HOSTCONF = "config.hosts" DEFAULT_HOST = "www" PARENT_HOST = … -
How to choose which model to initialize in Django
I'm working on an installable app for Django that would requires a user's ability to use it or replace it with a custom version that is a subclass from the same base class. This is very similar approach to how Django's Default User Model works. What I am looking to do is not have it generate the default model in the database if it's been overridden. Any suggestions on a strategy for this would be greatly appreciated. RB -
Switching from Django Registration to Token registration
I have a Django Rest/ Vue.js application. For now I am using regular Django authentication with registration and django_registration templates. But since I am using it for a SPA application, it seems awkward. So I tried to implement token authentication with 'rest_framework.authtoken'. I've managed to get my token but it seems that I have to rewrite all my back-end logic to make it works because since I am not logging in with Django, all of mine permissions aren't working anymore: class IsOwnReviewOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True return obj.restaurant_review.review_author == request.user class IsAuthorOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True return obj.review_author == request.user Is there a painless way to switch from Django REST authentication to token authentication so user can log in and log out straight from my SPA app? -
Is there any field which is opposite of is_superuser?
Well my problem is quite complicated I think. Actually I am making building a website and i have almost made complete login and sign up functionality and suddenly i noticed a strange behavior with my website. I was login with by admin on a tab and at the same i was logging in to my website and i notice that before logging in there was an option appearing for logout but i did not log in at that sport. When i clicked on the logout button then my superuser just log out. So that when a super user is login from admin site than every new user can see log out button so which can click and superuser will log out. What kind of logic i can apply after that when all the users are login and only logout button appear otherwise not. I am trying with the following code. Please help me if you can. -----base.html---- {% if user.is_active and user.is_authenticated and user.is_not_superuser %} <a href="{% url 'accounts:logout' %}" class="get-started-btn">Logout</a> {% endif %} {% else %} <a href="{% url 'accounts:signup' %}" class="get-started-btn">Get Started</a> {% endif %} -
What is the best way to manage/preserve querystrings in django?
So my question basically is the title, more specifically, what is the best way to preserve the current url's querystring(s), if you want to add some more parameters, like filters on the next page in django? Example: You are currently on this /search/?location=london&type=1 page, that is a search result page, and you want to sort the results, so you want the next url to be /search/?location=london&type=1&sorting_order=-date_created. The problem comes from the fact, that if you do a usual form submission, the url will be /search/?sorting_order=-date_created. I did some research and I realized that there are quite a few ways to solve this problem, I even figured out a way to do it myself: Option 1 - Send hidden form fields populated by the existing querystring parameters, when submitting the sorting form. Option 2-2.5 - Building the urls as this blogpost describe https://simpleisbetterthancomplex.com/snippet/2016/08/22/dealing-with-querystring-parameters.html Option 3 - Building the urls with javascript. So after all, I am seriously confused about the fact, that all these options feel a bit sketchy at best, and I couldn't really believe that there is no official, predefined way to solve such a common problem, so please tell me there is. -
Objects are not being added in m2m field using UpdateView Django
TL:DR All objects get vanished from many-to-many field upon updating using UpdateView. I have a model to represent an instance of recipe: class Recipe(models.Model): ... tags = models.ManyToManyField(Tag, related_name='recipes', blank=True) ... This model has a ModelForm: class CreateRecipeForm(forms.ModelForm): class Meta: model = Recipe fields = (..., 'tags') A view class is a heir of UpdateView and looks like following: class ChangeRecipe(UpdateView): template_name = 'change_recipe.html' form_class = CreateRecipeForm success_url = reverse_lazy('index') model = Recipe def form_valid(self, form): new_tags = [name for name in ('breakfast', 'lunch', 'dinner') if name in self.request.POST] ... for tag in form.instance.tags.all(): if not tag.name in new_tags: form.instance.tags.remove(tag) else: new_tags.remove(tag.name) for name in new_tags: form.instance.tags.add(Tag.objects.get(name=name)) ... The tag m2m field is renered this way: <div class="tags__item"> {% for tag, tag_value in form.tags.field.choices %} <div class="tags__item"> <input type="checkbox" name="{{ tag.instance.name }}" id="id_{{ tag.instance.name }}" class="tags__checkbox tags__checkbox_style_{{ tag.instance.style }}" {% if tag.instance in form.instance.tags.all %}checked="checked"{% endif %}> <label for="id_{{ tag.instance.name }}" class="tags__label">{{ tag.instance.template_name }}</label> </div> {% endfor %} </div> The proble as mentioned in TL:DR is that all objects simply get removed from the m2m field leaving it blank. I checked if checkboxes are properly delivered with request.POST and yes, they are. I am getting all names and Tag objects … -
Instabot :: Django , How To cache bot.login in instabot for multiple account and use anytime i want without relogin again
Instabot :: Django , How To cache bot.login in instabot for multiple accounts and use anytime i want without relogin again ! -
django update function based view of multiple models
I have a parent model and two children models and I made a view to add multiple children to one parent but I'm getting confused about making an update view for the parent with all children this is the form to create multiple children views.py def create_day_view(request,pk): mydate = get_object_or_404(MyDate,pk=pk) if request.method == 'POST': length = request.POST.get('length') sof_zman_1 = request.POST.get('sof_zman_1') sof_zman_2 = request.POST.get('sof_zman_2') sof_zman_tefila = request.POST.get('sof_zman_tefila') ad_image = request.POST.get('ad_image') day_details = MyDateDetails.objects.create( date = mydate, sof_zman_1 = sof_zman_1, sof_zman_2 = sof_zman_2, sof_zman_tefila = sof_zman_tefila, ad_image = ad_image, ) for file_num in range(0, int(length)): Image.objects.create( date = mydate, image = request.FILES.get(f'images{file_num}') ) context = {'mydate': mydate} return render(request, 'luach/create_day.html',context=context) I'm sharing the template so you will understand how the form works create_day.html {% extends 'luach/base.html' %} {% block content %} <div class='container'> <div class="jumbotron myjumbotron"> <div class="p-3 mb-2 bg-light text-center " style="border-radius: 10px;"> <h1 class='title-date text'>{{mydate.hebrew_date}}</h1> <h4 class='english-date'>{{mydate.english_date}}</h4> </div> <label>sof zman 1</label> <div class="row"> <div class="col"> <input type="time" id="sof_zman_1" class="form-control"> </div> <div class="col"> </div> </div> <label>sof zman 2</label> <div class="row"> <div class="col"> <input type="time" id="sof_zman_2" class="form-control"> </div> <div class="col"> </div> </div> <label>sof zman tefila</label> <div class="row"> <div class="col"> <input type="time" id="sof_zman_tefila" class="form-control"> </div> <div class="col"> </div> </div> <br> <!--<label>ad image</label> <input … -
How do I load multiple product images with a selection of the main image without reloading the page?
I am creating a product creation (editing) page. A product can have many images (one of which is the main one). According to my idea, the user fills out the form, selects images using the tag element " with multiple choice", and among the uploaded images selects the main image (I tried to do this using https://rvera.github.io/image-picker /). After pressing the SUBMIT button, all data is saved. How to implement this with Django? I thought it was a popular problem, but I couldn't google simple solutions. The problem is complicated by the fact that I use Django Forms with "__all__" fields, but this is not necessary, I am tired of trying and agree to any solution to my problem :( I have models: class Product(models.Model): name = models.CharField(max_length=100) class Image(models.Model): image = models.ImageField(upload_to="web/products/") isMainImage = models.IntegerField() product = models.ForeignKey(Product, on_delete=models.PROTECT) views.py def product_edit(request, id): product = get_object_or_404(Product, pk=id) form = ProductForm(request.POST, instance=product) if request.method == "POST": form = ProductForm(request.POST, instance=product) if form.is_valid(): form.save() return render(request, "product.html", {'form': form}) forms.py class ProductForm(forms.ModelForm): class Meta: model = Product fields = ('__all__') product.html <form method="POST" class="post-form" enctype="multipart/form-data">{% csrf_token %} {{ form.as_p }} // i want put here INPUT for file uploading <button type="submit" … -
What is "Verbose_name" and "Ordering" in class Meta? And please explain a little about Meta Class in django
''' from django.db import models import uuid class Book(models.Model): name=models.CharField(max_length=100) isbn=models.UUIDField(default=uuid.uuid4, primary_key=True) writer=models.CharField(max_length=100) class Meta: ordering=['name'] ordering='User MetaData''' -
Django static files not serving when running inside Docker container
I have a django application thats is rendering the static files when run outside docker container. I added a Dockerfile so that I can run it in a container. However, the static files are not getting served when running in the container The sample app that I have used can be found here I have added the following Dockerfile at the root level FROM python:3.8 #add project files to the usr/src/app folder ADD . /usr/src/app #set directoty where CMD will execute WORKDIR /usr/src/app/wisdompets COPY requirements.txt ./ # Get pip to download and install requirements: RUN pip install --no-cache-dir -r requirements.txt # Expose ports EXPOSE 8000 # default command to execute CMD exec gunicorn wisdompets.wsgi:application --bind 0.0.0.0:8000 --workers 3 And the requirements.txt file at root level as below django==3.0.3 gunicorn==20.0.4 The static files settings in my settings.py is as follows STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] Please let me know if there's something wrong with my configuration -
How can I reveal my truncated text in Django?
I am creating a blog app with Django where users can upload articles, and I would like to truncate the users text to a max length of 150 chars, but give readers the option of expanding the text by clicking 'read more'. {% for post in posts %} <p>{{ post.content|truncatechars:150 }}<span>read more</span></p> {% endfor %} I am able to truncate the text but cannot work out how to then expand it on click. I would like the expanded text to be revealed within the same div, and not be redirected to another page. Any help would be much appreciated. Thanks in advance -
How to authenticate websocket with django channels?
The application stack looks like this: Backend: Django DRF + Channels, for authentication i'm using: 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ), Frontend (not served by django backend) : Vue JS application, using a generated client (@openapitools/openapi-generator-cli") library to authenticate / execute operations on the backend. I can use the rest based authentication, retrieve a token that I can use for the following rest-api calls, but I would like to use that token as well with the vue websocket <-> django channels communication. The problem is: How do I use authentication on the channels consumer? If I log in to the django admin page, the incoming websocket connection immediately recognized the admin user in the scope, but not if I'm using any other authentication. What I'm seeing here, is using the default admin page login, it will save the sessionid and a csrf token as cookies. When I try to replicate the same authentication behaviour a with client api call, I can see on the browser network traffic that the proper Set-Cookies are sent, containing this info, but it is unreachable for me to set. Should it be set by default? What am I missing? -
nginx with gunicorn and django on centos 7
I'm trying to make my nginx and gunicorn start working... but seemingly trying everything I could do, fails... If I do: systemctl restart nginx systemctl status nginx It shows green, and it works... If I do: systemctl start gunicorn.socket systemctl status gunicorn.socket -l It shows green and works fine... But if I do: systemctl start gunicorn.service systemctl status gunicorn.service -l it shows me the following message: gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: disabled) Active: failed (Result: exit-code) since Thu 2020-09-10 14:17:23 UTC; 15min ago Process: 22145 ExecStart=/home/scorg/pro/sc_project/bin/gunicorn --workers 3 --bind unix:/home/scorg/pro/projects/sc/sc.sock sc.wsgi:application (code=exited, status=3) Main PID: 22145 (code=exited, status=3) Sep 10 14:17:23 gunicorn[22145]: File "<frozen importlib._bootstrap>", line 1014, in _gcd_import Sep 10 14:17:23 gunicorn[22145]: File "<frozen importlib._bootstrap>", line 991, in _find_and_load Sep 10 14:17:23 gunicorn[22145]: File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked Sep 10 14:17:23 : ModuleNotFoundError: No module named 'sc' Sep 10 14:17:23 : [2020-09-10 14:17:23 +0000] [22152] [INFO] Worker exiting (pid: 22152) Sep 10 14:17:23 : [2020-09-10 14:17:23 +0000] [22145] [INFO] Shutting down: Master Sep 10 14:17:23 : [2020-09-10 14:17:23 +0000] [22145] [INFO] Reason: Worker failed to boot. Sep 10 14:17:23 : gunicorn.service: main process exited, code=exited, status=3/NOTIMPLEMENTED Sep 10 14:17:23 : Unit gunicorn.service … -
HINT: Add or change a related_name argument to the definition for 'CustomUser.user_permissions' or 'User.user_permissions'
I need help. I´m creating an app in Django and I'm having some trouble making migrations of my custom user's class. The error is: ERRORS: auth.User.groups: (fields.E304) Reverse accessor for 'User.groups' clashes with reverse accessor for 'Usuario.groups'. HINT: Add or change a related_name argument to the definition for 'User.groups' or 'Usuario.groups'. auth.User.user_permissions: (fields.E304) Reverse accessor for 'User.user_permissions' clashes with reverse accessor for 'Usuario.user_permissions'. HINT: Add or change a related_name argument to the definition for 'User.user_permissions' or 'Usuario.user_permissions'. usuarios.Usuario.groups: (fields.E304) Reverse accessor for 'Usuario.groups' clashes with reverse accessor for 'User.groups'. HINT: Add or change a related_name argument to the definition for 'Usuario.groups' or 'User.groups'. usuarios.Usuario.user_permissions: (fields.E304) Reverse accessor for 'Usuario.user_permissions' clashes with reverse accessor for 'User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'Usuario.user_permissions' or 'User.user_permissions'. Now, this is my code: My Model: class CustomUser(AbstractUser): email = models.EmailField(unique=True, max_length=80) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['USERNAME'] def __str__(self): return self.email class Perfil(models.Model): user=models.OneToOneField(CustomUser, related_name="usuario_user" , on_delete=models.CASCADE) nacionality= models.ForeignKey(Paises, on_delete=models.DO_NOTHING) rol= models.ForeignKey(Rol, on_delete=models.DO_NOTHING) def str(self): return self.CustomUser birth_date=models.DateField() In my settings.py: AUTH_USER_MODELS= 'users.CustomUser' LOGIN_REDIRECT_URL= reverse_lazy('home') LOGOUT_REDIRECT_URL= reverse_lazy('login') LOGIN_URL = reverse_lazy('login') # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'apps.users', ]``` -
ReactJs 400 (Bad Request)
My django rest framework returns a 400 bad request when sending files across with ReactJs, while postman uploads the same file with same parameter successfully. When I investigated further, I noticed a specific error of "No file was submitted" was what was returned from the API. Submit Handler submitHandler(event){ event.preventDefault() const data = new FormData() data.append('file', this.state.selectedFile) axios .post('http://localhost:8000/files/', data, {}) .then(res => { console.debug(res.statusText) }) .catch(err => { console.debug(err) }) } state: this.state = { selectedFile: null, redirect: false, file_name:'', }