Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to insert raw html into form when creating a page using django
I want to include things like hyperlinks, quoting, italicized text, etc. into my pages I post on the site I wrote with django but it seems to escape my code. What can I do to add this feature? Has someone else already done something I could just use? -
Error: Has No Attribute "Getlist" Error When Making Request in Django
When I run the tests to make requests to the webpage on Django, the tests run fine and have expected behavior. However, when the same code is run when I'm making a request outside of the testing environment in Django, running: request.data.getlist("insert_key_here") where "insert_key_here" is a key from a key-value pair where the value is a list, I get this error: 'dict' object has no attribute 'getlist' When I try to run this instead request.data["insert_key_here"] I get an error that a string's indices must be an int. Does this mean that the request.data is somehow a string? If it was just grabbing the first value in the list like how it would if you used .get() instead of .getlist(), I don't know that I'd be getting this error just from trying to fetch the value. To give some context, this is an example of the format of the request: { "insert_key_here" : [ "list_item1", "list_item2" ] } I'm not sure why it would work perfectly in the testing environment, but, then, when I run it outside the testing environment, I get that error on that specific line. -
I couldn't able to save my data in to admin. it just redirect me to Home page
This is my View.py code. hear it redirect me to home page and doesn't save my data in to admin panel. **if i indent back else condition Blockquote else: form = OrderForm() return redirect('home') Blockquote it gives me error - ValueError at /orders/place_order/ The view orders.views.place_order didn't return an HttpResponse object. It returned None instead.** def place_order(request, total=0, quantity=0,): current_user = request.user # if cart count is less then 0 or equel to 0, then redirect to shop cart_items = CartItem.objects.filter(user=current_user) cart_count = cart_items.count() if cart_count <= 0: return redirect('store') grand_total = 0 tax = 0 for cart_item in cart_items: total += (cart_item.product.price*cart_item.quantity) quantity += cart_item.quantity tax = (12 * total)/100 grand_total = total + tax if request.method == 'POST': form = OrderForm(request.POST) if form.is_valid(): # store all the information inside belling table data = Order() data.user = current_user data.first_name = form.cleaned_data['first_name'] data.last_name = form.cleaned_data['last_name'] data.phone = form.cleaned_data['phone'] data.email = form.cleaned_data['email'] data.address_line_1 = form.cleaned_data['address_line_1'] data.address_line_2 = form.cleaned_data['address_line_2'] data.country = form.cleaned_data['country'] data.provence = form.cleaned_data['provence'] data.zone = form.cleaned_data['zone'] data.district = form.cleaned_data['district'] data.order_note = form.cleaned_data['order_note'] data.order_total = grand_total data.tax = tax data.ip = request.META.get('REMOTE_ADDR') data.save() # genarate order no yr = int(datetime.date.today().strftime('%y')) dt = int(datetime.date.today().strftime('%d')) mt = int(datetime.date.today().strftime('%m')) d = datetime.date(yr,mt,dt) current_date = … -
Django how to import custom javascript?
I'm having the weirdest issue yet; I can't request a custom javascript (chart.js) the same way I do another one (main.js); This is how I request the scripts; notice how main.js is in the same folder as chart.js Now, the requests received by Django; notice how main.js is ok, while chart.js is 404: I've tried deleting the __pycache__ folders and restart the server but no go. What could be causing this? -
Protected routes using JWT tokens in NextJS + Django
I'm starting this new NextJS application where I'm using Django as an API. I'm using JWT tokens for authentication/authorization and I wanted to create protected routes. After following a bunch of tutorials, videos and other things online, here's what I came up with: I created an axios instance (api.js) (where I was trying to intercept requests to set the Authorization header): import axios from "axios"; import Cookies from "js-cookie"; const api = axios.create({ baseURL: "http://127.0.0.1:8000/api/", headers: { Accept: "application/json", "Content-Type": "application/json", }, }); api.interceptors.request.use((request) => { const token = Cookies.get("accessToken"); if (token) { api.defaults.headers.Authorization = `Bearer ${token.access}`; } return request; }); export default api; And an AuthService.js (where I set a cookie when l log in): import Cookies from "js-cookie"; import api from "./api"; export const AuthService = { login: async (email, password) => { const { data: token } = await api.post("token/", { email, password }); console.log(token); if (token) { console.log("Got token"); Cookies.set("accessToken", token.access, { expires: 60 }); api.defaults.headers.Authorization = `Bearer ${token.access}`; const { data: user } = await api.get("users/current/"); console.log("Got user", user); return user; } }, logout: async () => { Cookies.remove("accessToken"); delete api.defaults.headers.Authorization; }, getUser: async () => { try { const { data: user } = … -
Django Saving Model Method Property to the Database
I have ModelOne that has a model method, lets say method_that_does_stuff, with the @property decorator that calculates a boolean value, based on the value of ModelThree, which is a ForeignKey of ModelTwo, which is a ManyToMany of ModelOne. I'm trying to make it that when the value of method_that_does_stuff changes, due to changes in ModelThree, it saves the boolean value to ModelOne. Below is my implementation: from django.db import models class ModelThree (models.Model): some_input = models.TextField() model_two = models.ForeignKey(ModelTwo, on_delete=models.CASCADE) class ModelTwo (models.Model): name = models.CharField(max_length=200) class ModelOne (models.Model): name = models.CharField(max_length=200) boolean_field_to_change = models.BooleanField(default=False) model_twos = models.ManyToManyField(ModelTwo) @property def method_that_does_stuff(self): # It does some stuff and returns either True or False, but let's assume True # The True or False return depends on ModelThree's some_input field # If the some_input field doesn't change, then it will stay False return True def save(self, *args, **kwargs): self.boolean_field_to_change = self.method_that_does_stuff super(ModelOne, self).save(*args, **kwargs) However, for some reason, when I run in the Django shell and get all of the ModelOne objects, the method_that_does_stuff will be True, but the boolean_field_to_change will still be its default value of False. I found this solution: Django Model Method or Calculation as Field in Database which is … -
from autoslug import AutoSlugField Not working
please I need help with Python Django stuff I have installed pip install pillow and I need to import it in models.py. When I run this code in command prompt, I get this error[At line:1 char:1 from autoslug import AutoSlugField The 'from' keyword is not supported in this version of the language. + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordEx ception + FullyQualifiedErrorId : ReservedKeywordNotAllowed]1 I am using Python 3.10 with Django 4.0.1 on Windows 10 64bits I will appreciate your help to solve this -
Query selector sort
Inbox = Messages.objects.filter(Q(sender=request.user) | Q(receiver=request.user)) context['Inbox'] = Inbox Currently I am using this to grab all messages for the currently logged in user. I want to sort it by time and read status. So that the lastest unread message shows up first. models.py class Messages(models.Model): sender = models.ForeignKey(Profile,related_name='sender',on_delete=models.CASCADE) receiver = models.ForeignKey(Profile,related_name='receiver',on_delete=models.CASCADE) subject = models.CharField(default='',max_length=100) text = models.CharField(default='',max_length=4096) time = models.DateTimeField(auto_now_add=True) read = models.BooleanField(default=False) def __str__(self): return '{} to {} :{}'.format(self.sender,self.receiver,self.text) -
I cannot get images to work on my django project(this is my first one and im having trouble)
I have an img folder in the same directory as my html files. I want to put images onto my site but I am doing something wrong. this is the code: {% block a %} <div class="row"> <div class="col-sm-4 center"> <img src="img/img01.jpeg"> </div> </div> {% endblock %} this is what happens when I run the local server. local server this is my file directory file directory -
Difficulty in partial update in DRF
I am learning Django and DRF, I am having issues updating the field expire_on. And there also I have to put the logic to prevent to put the value of expore_on no greater than 7 days from created_on. I am having trouble figuring out how to update the same and write the above logic. I have tried: update function in DRF viewset.Viewset Django Rest Framework not showing form fields for PATCH/PUT request Django REST Framework doesn't display value in PUT form Django form fields not showing up Models class Url_data(models.Model): uri_id = models.AutoField(primary_key=True) actual_url = models.URLField() created_on = models.DateTimeField( auto_now_add=True, editable=False, auto_now=False) expire_on = models.DateTimeField() short_url = models.URLField(max_length=200, editable=False) clicks = models.PositiveBigIntegerField( default=0, editable=True, blank=True) Serializer class Url_dataSerializer(serializers.ModelSerializer): class Meta: model = Url_data fields = '__all__' read_only_fields = ['short_url', 'created_on', 'clicks'] class ExpireDateUpdateSerializer(serializers.ModelSerializer): class Meta: model = Url_data fields = ('expire_on', ) View class UrlList(generics.ListCreateAPIView): queryset = Url_data.objects.all() permission_classes = [permissions.IsAuthenticatedOrReadOnly] serializer_class = Url_dataSerializer class UrlDetail(generics.RetrieveDestroyAPIView): queryset = Url_data.objects.all() permission_classes = [permissions.IsAuthenticatedOrReadOnly] serializer_class = Url_dataSerializer class ExpireDateUpdate(generics.UpdateAPIView): queryset = Url_data.objects.all() permission_classes = [permissions.IsAuthenticatedOrReadOnly] serializer_class = ExpireDateUpdateSerializer Error 405 Undocumented Error: Method Not Allowed **Response body** { "detail": "Method \"PATCH\" not allowed." } **Response headers** access-control-allow-origin: * allow: GET,DELETE,HEAD,OPTIONS content-length: 42 … -
Can't manage to post an object via axios to django - possibly due to AnonymousUser object?
I'm trying to add a button in React which posts an object to django via axios when a user clicks on it. However, it seems like something's wrong backend. Here's the button: <button id="add-rat" type="button" className="btn homeButton" onClick={ (e) => submit(e) } > Add rat </button> And here's the axios, in the same page: const submit = (e) => { const name = "namee"; const eyeColour = "Red"; const bodyColour = "White"; const bio = "hfff"; const image = "lineart.PNG"; const data = { name: name, eye_colour: eyeColour, body_colour: bodyColour, bio: bio, image: image, }; e.preventDefault(); console.log(data); const token = localStorage.getItem("token"); axios .post("http://127.0.0.1:8000/api/addObject", data, { headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json", }, }) .then((res) => { console.log(res.data); }) .catch((err) => console.log(err)); }; This is my console output: {name: 'namee', eye_colour: 'Red', body_colour: 'White', bio: 'hfff', image: 'lineart.PNG'} myRats.js:86 {res: 'Error Accured'} (myRats.js:86 btw, is console.log(res.data); ) Here's my view for the object: class AddRat(APIView): def post(self,request): data = request.data user = request.user print(data) try: user = rat( name = data['name'] , body_colour = data['bodyColour'] , eye_colour = data['eyeColour'],user= user, bio = data['bio'] , image = data['image']) user.save() return Response({'res':"Rat Saved Successfully"}) except: return Response({'res':"Error Accured"}) def get(self,request): user = … -
real time chat app with django workds with channels but not after using redis and deploy to heroku
hello I am working on chatting app with django channels works perfectly in localhost but once I used redis and deployed to heroku I can't send anymessage the websocket always close, my settings.py CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [os.environ.get('REDIS_URL', 'redis://localhost:6379')], }, }, } I am using redis and postgresql addons, and my Procfile is like this web: daphne myproject.asgi:application --port $PORT --bind 0.0.0.0 -v2 worker: python manage.py runworker --settings=myproject.settings -v2 why it works perfectly in my localhost because I am using only this CHANNEL_LAYERS = { "default": { "BACKEND": 'channels.layers.InMemoryChannelLayer' } } -
Django Models, I have nested categories, what is the best way to make sure that each object will "respond" to it's category and the parent categories?
I have a model for nested categories that I found online and is working really nicely: class Category(models.Model): parent = models.ForeignKey('self', related_name='children', on_delete=models.CASCADE, blank=True, null=True) title = models.CharField(max_length=100) class Meta: unique_together = ('title', 'parent') def __str__(self): full_path = [self.title] k = self.parent while k is not None: full_path.append(k.title) k = k.parent return '/'.join(full_path[::-1]) I also have an another model, "standard" model that has a category field (up to this moment it was simply foreign key). My problem is, what is the "proper" way to make sure that object will respond to more than one category here? I mean, if I have a Fiat/Opel/Ferrari object, and I have categories like that: Means of Transport Land Transport Cars Sea Transport Then I will assign to my "Fiat/Opel/Ferrari" object category "Cars" but I also want it to respond to categories "Land Transport" and "Means of Transport". I am wondering what is the best/most efficient way to do this. Currently I have ideas like: each category have by default empty fields like grandparent, grand-grandparent etc. that I will fill out and add to querying stuff. My Category could be ManytoMany instead of foreign key and I would manually set all the categories. I don't … -
Django rest framework - Foreign key - one to many relation
For my project I need to have a simple process a form => many questions => for each questions a response type => if the response type is a multiple choice, then possible response are in a uniq group. My goal is to be able to push though DRF/Django rest framework the whole initial form. Here are my models: class FormModels(models.Model): class Status(models.IntegerChoices): DRAFT = 1, _("DRAFT") PUBLISHED = 2, _("PUBLISHED") ARCHIVED = 5, _("ARCHIVED") form_name = models.CharField(unique=True, blank=False, null=False, max_length=255) form_model = models.CharField(unique=True, blank=False, null=False, max_length=255) status = models.IntegerField(choices=Status.choices, blank=False, null=False, default=1) def __str__(self): return self.form_name class FormResponseTypeModels(models.Model): class Type(models.IntegerChoices): TEXT = 1, _('TEXT') MULTICHOICE = 2, _('MULTI') type = models.IntegerField(choices=Type.choices, blank=False, null=False, default=1) group = models.IntegerField(blank=False, null=True, default=1) def __str__(self): return str(self.type) class Meta: constraints = [ UniqueConstraint(fields=['group'], name='unique_group') ] class MultipleChoiceDataModels(models.Model): text = models.CharField(blank=False, null=False, max_length=255) value = models.CharField(blank=False, null=False, max_length=255) order = models.IntegerField(blank=False, null=False, default=1) group_refid = models.ForeignKey(blank=False, null=False, default=1, to=FormResponseTypeModels, to_field="group", related_name="groups", on_delete=models.PROTECT) def __str__(self): return self.text class FormQuestionModels(models.Model): form_id = models.ForeignKey(to=FormModels, on_delete=models.PROTECT) form_response_type = models.ForeignKey(to=FormResponseTypeModels, on_delete=models.PROTECT, related_name="test") form_question = models.TextField(max_length=2000) def __str__(self): return self.form_question Here is my serializers.py class FormMultipleChoiceDataSerializer(serializers.ModelSerializer): class Meta: model = MultipleChoiceDataModels fields = "__all__" depth = 10 class FormResponseTypeSerializer(serializers.ModelSerializer): groups … -
Django mod_wsgi daemon mode touch wsgi.py not triggering refresh
I cannot reload django templates by touching the wsgi.py script located in my django application root/application name. The script and project are located under /var/www, so I need sudo to execute touch. I am running production apache2 server running a django website with mod_wsgi in daemon mode. I can collectstatics and make migrations, access database (without permission issues). I can also change the DEBUG flag in the settings. If I touch wsgi.py, it will put the production site into debug as expected, but the htmls are not loaded. Likewise I can update the static files, collectstatics, or modify the underlying models and see the changes live. Likewise I can use the commented code to retrieve what Daemon mode the swerver is running in. Its only the templates causing an issue. The settings file, wsgi.py, statics and python scripts are responded as expected. Has anyone got any idea how to debug this? virtualenv python3.8.12 apache2.4 mod_wsgi compiled for python3.8.12 wsgi.py import os import sys from django.core.wsgi import get_wsgi_application sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "../../"))) sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "../"))) sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "../app/"))) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mb.settings') application = get_wsgi_application() #def application(environ, start_response): # status = '200 OK' # if not environ['mod_wsgi.process_group']: # output = u'EMBEDDED MODE' # else: … -
Made a simple blogging site with django, original posts that were made with manage.py exists and resolve, new posts with nginx/uwsgi do not resolve
I wrote a simple django website that seemed to completely work when running it with manage.py. I have since set up the site to run off of nginx/uwsgi and now new posts show up on the front page, but when I try to go to the page to reveal the blog post details I get a Not Found page. Can anyone help me figure out what I have done wrong? Here is my blog/urls.py from django.urls import path from . import views app_name = "blog" urlpatterns = [ path('', views.index, name='index'), path('<int:welcome_id>/', views.welcome_detail, name='welcome_detail'), path('blog/<int:category_id>/', views.category, name="category"), path('blog/<int:category_id>/<int:blog_id>/', views.blog_post_detail, name="blog_detail"), ] Here is my blog/views.py from django.shortcuts import render from django.template import loader from django.http import HttpResponse, Http404 from .models import WelcomePage, BlogPost, Categories def index(request): latest_welcome_message = WelcomePage.objects.order_by('id') latest_blog_posts = BlogPost.objects.order_by('id') categories = Categories.objects.order_by('id') template = loader.get_template('blog/index.html') context = {'latest_welcome_message' : latest_welcome_message, 'latest_blog_posts' : latest_blog_posts, "categories" : categories} return render(request, 'blog/index.html', context) def welcome_detail(request, welcome_id): try: welcome_message = WelcomePage.objects.get(pk=welcome_id) except WelcomePage.DoesNotExist: raise Http404("Question does not exist") return render(request, 'blog/detail.html', {'welcome_message':welcome_message}) def category(request, category_id): try: category = BlogPost.objects.get(categories=category_id) blogs_of_category = BlogPost.objects.all() except BlogPost.DoesNotExist: raise Http404("Blog does not exist") return render(request, "blog/category.html", {"category_id":category_id, "category":category, "blogs_of_category":blogs_of_category}) def blog_post_detail(request, category_id, blog_id): try: blog_post_detail … -
Polymorphic queryset in a Django ListView renders the template as many time as objects have the queryset
I have a polymorphic model using the polymorphic library on Django with one ParentModel and several ChildModel and I want to use the parent model with all his children in a queryset the queryset that I am using in my ListView is something like this <PolymorphicQuerySet [<ChildModel1: model description>, <ChildModel2: model description>]> But when my list view render my template, it renders my template as many time as child objects have if I have one object from ChildModel1, one from ChildModel2, and one from ChildModel3 it renders my HTML three times on the same screen one below another -
Don't start a thread in ASGI django while in manage.py
I am using Django 4.0.1 with the channels extension, so I'm using the ASGI interface. In one of my applications, I'm using it's AppConfig.ready() method to start a thread / asnyc loop - specifically the paho.mqtt package via loop_start(). If a message arrives on a subscribed topic, this application handles some business logic. This works fine for my usecase - with the exception of two problems: It's also started when I use any manage.py command. ./manage.py runserver (with reload enabled) will spawn a second process, which results in two connections being made - and I only need one. While I could use a filesystem-mutex to block the execution of a second application, I'd like to know, if there's a more "Django way" of solving this? -
Simple Math on One Webpage
I'm currently trying to do something as basic as adding two numbers the user inputs onto the page and showing the result on the same page but I'm running into problems. index.html {% extends "project_long_page/base.html" %} {% block body %} <form action="." method="POST"> {% csrf_token %} {{ forms }} <input type="submit"> </form> {% endblock %} views.py from django.shortcuts import render import datetime from django import forms from django.shortcuts import render class NewTaskForm(forms.Form): num1 = forms.IntegerField(label="Number 1") num2 = forms.IntegerField(label="Number 2") # Create your views here. def index(request): return render(request, "project_long_page/index.html") def add(request): return render(request, "project_long_page/index.html", { "form": NewTaskForm() }) urls.py from django.urls import path from . import views app_name = "project_long_page" urlpatterns = [ path("", views.index, name="index") ] Current Webpage Output Desired Webpage Output (While keeping original values inputted) Thank you for helping if you assist :,) Edit: In case you want to see this... -
XAMPP with WSGI not rendering django page
I am trying to run django on XAMPP Apache server and followed the steps mentioned here. Here are the changes in Apache config: When access the application in browser below is the result instead of django page: Please help what I am missing in this ? -
CustomUserCreationForm doesn't work in django
I am working on user registration app in django. I can write in inputs, but when I click submit button it doesn't do anything. My views.py file is: from django.urls import reverse_lazy from django.views import generic from .forms import CustomUserCreationForm class SingupPageView(generic.CreateView): form_class = CustomUserCreationForm success_url = reverse_lazy("login") template_name = "registration/singup.html" My urls.py file is: from django.contrib import admin from django.urls.conf import path from . import views urlpatterns = [ path("singup/", views.SingupPageView.as_view(), name="singup"), ] My admin.py file is: from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from .forms import CustomUserCreationForm, CustomUserChangeForm CustomUser = get_user_model() class CustomUserAdmin(UserAdmin): add_form = CustomUserCreationForm form = CustomUserChangeForm model = CustomUser list_display = ['email', 'username',] admin.site.register(CustomUser, CustomUserAdmin) My singup.html file is: {% extends '_base.html' %} {% block title %}Sing Up{% endblock title %} {% block content %} <h2>Sing Up</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="button">Sing Up</button> </form> {% endblock content %} -
How to submit a form with django ajax without parsing the input
I have a modal form that I use when users need to create something without leaving the page they are on. And to avoid refreshing the page after the modal form submission, I am using ajax to submit the form. For a series of reasons, I can't parse the form field by field so I was trying to find a way to get all the form data and submit them with a "general" approach and then process the post-request in my view (populate the form with the POST). However, the approach I am using is not working and I was hoping someone had an alternative idea. <body> <!--Modal --> <div class="modal fade" tabindex="-1" role="dialog" id="modal"> <div class="modal-dialog" role="document"> <div class="modal-content"> <!-- Popup --> <div class="pop-up-form"> <div class="pop-up-form__wrp"> <!-- Title --> <div class="pop-up-form__title-wrp"> <h2 class="pop-up-form__title">Create New</h2> </div> <!-- END Title --> <!-- Form --> <form class="pop-up-form__form" id="form"> {% csrf_token %} {% for field in form %} <div class="pop-up-form__input-wrp"> <label class="pop-up-form__label" for="{{ field.id_for_label }}">{{ field.label }}</label> {{ field|add_class:"pop-up-form__input" }} {% for error in field.errors %} <p class="help-block">{{ error }}</p> {% endfor %} </div> {% endfor %} <!-- <div class="form-group{#% if field.errors %#}invalid{#% endif %#}"></div> --> <!-- BTNs --> <div class="pop-up-form__btn-wrp"> <button data-dismiss="modal" … -
Django Rest Framework ModelViewSet When Posted?
I have a simple rest application. models.py : class Check(models.Model): crypted = models.TextField() anid = models.IntegerField() def __str__(self): return str(self.anid) serializers.py : class CheckSerializer(serializers.ModelSerializer): class Meta: model = Check fields = ['crypted', 'anid'] views.py : class CheckViewSet(viewsets.ModelViewSet): serializer_class = CheckSerializer queryset = Check.objects.all() urls.py : router = routers.DefaultRouter() router.register('all', CheckViewSet) urlpatterns = [ path('', include(router.urls)), ] Here is what I need : I need to make a code run "when I posted into this page" How can I provide this? -
SQLite3 Integrity Error When Running "createsuperuser"
I am trying to extend the default Django User model by linking to it through a OneToOneField. I successfully migrated the changes and registered my Profile model inside admin.py, however, when I try to run the command python manage.py createsuperuser and fill in the information I get an Integrity Error. django.db.utils.IntegrityError: NOT NULL constraint failed: accounts_profile.date_of_birth I know what the issue is. I have a field called date_of_birth which is required, and I can't leave it blank, that raises the exception. I want a simple solution, but couldn't think of one, and I don't want to add a bunch of blank=True snippets to all of my required fields. Here's my code. models.py from django.contrib.auth.models import User from django.db import models class Language(models.Model): # - [ CHOICES ] - # name = models.CharField(max_length=20) # - [ METHODS ] - # def __str__(self): return self.name class Skill(models.Model): # - [ CHOICES ] - # name = models.CharField(max_length=20) # - [ METHODS ] - # def __str__(self): return self.name class Profile(models.Model): # - [ CHOICES ] - # GENDER_CHOICES = [ ('Female', 'Female'), ('Male', 'Male') ] EDUCATIONAL_LEVEL_CHOICES = [ ('None', 'None'), ('Primary School', 'Primary School'), ('Secondary School', 'Secondary School'), ('High School', 'High School'), … -
Django Rest - Post Data and File
I have two models like so: class Tool(...): name = models.CharField(unique=True, ...) class Dataset(...): file = models.FileField(...) tool = models.ForeignKey(...) I want to send a post request such that I can create a Dataset instance, upload a file and specify which Tool the instance belongs to. Furthermore, it would be ideal if I could use the Tool name (which is unique) when sending the post request. So far I can upload a file successfully if I remove the tool from the DatasetSerializer. But when I add the tool to the DatasetSerializer I get a 400 Bad Request error without any further details in the console. Here are my serializers and views files: serializers.py class ToolSerializer(serializers.ModelSerializer): ... class DatasetSerializer(serializers.ModelSerializer): tool = ToolSerializer() class Meta: model = models.Dataset fields = ['tool', 'file', ...] views.py from rest_framework.parsers import MultiPartParser class DatasetViewSet(viewsets.BaseModelViewSet): parser_classes = [MultiPartParser] ... And here is the request I am trying to do: # I am using the tool id here, but would prefer to use the name requests.post( ... data = { 'tool' : 1 }, files = { 'file' : open('file/path','rb') } )