Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Passing data from form in html to views.py not working
I passed the id value from html form to views .py. I want to check if the value matches with the one in database. But for some reason it's not working. list.html <form method= 'POST' action = "{% url 'jobs:pinned'%}"> {% csrf_token%} <input type ="text" name = "number"> <input type="submit" value="Submit"> </form> views.py def pinned(request,category_slug=None): users = User.objects.exclude(id=request.user.id) jobs_list1 = Jobs.objects.all() if request.method =="POST": vari = request.GET.get('number') for evert in jobs_list1: if evert.Job_Id == vari: evert.flag = True evert.save(update_fields=["flag"]) context = { 'job_list1':jobs_list1, 'users':users } return render(request, 'jobs/product/list.html',context) Here, if i put a static value as 511, i.e if evert.Job_Id ==511, it works. But if i change it to request.GET.get('number'), it's not working. How do i send value from form input value to views.py. Thanks. -
how to write logic of applying coupons in django rest framework?
Please tell me how to write logic of applying coupons . Im attaching my code here: class Coupon(models.Model): code = models.CharField(max_length=50, unique=True) valid_from = models.DateTimeField() valid_to = models.DateTimeField() discount = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(100)]) active = models.BooleanField() def __str__(self): return self.code class CustOrder(models.Model): ........... ............ coupon = models.ForeignKey(Coupon, on_delete=models.SET_NULL, null=True) class CouponViewSet(viewsets.ModelViewSet): queryset = Coupon.objects.all() permissions_classes = [ permissions.AllowAny ] serializer_class = CouponSerializer class CouponSerializer(serializers.ModelSerializer): class Meta: model = Coupon fields = '__all__' -
How to extract and save files from PDF in a Django Model
I'm working on a project right now that needs to extract PDFs attached to a Model. The PDFs are then related to the Project as the below models.py: class Project(models.Model): name = models.CharField(max_length=100) files = models.FileField('PDF Dataset', help_text='Upload a zip here', null=True) class Pdf(models.Model): name = models.CharField(max_length=100) file = models.FileField(null=True) project = models.ForeignKey(Project, on_delete=models.CASCADE) I then have a task I can trigger via Celery to extract the PDF and save each as its own record. My sample tasks.py below: from django.core.files.base import ContentFile from celery import shared_task from zipfile import ZipFile import re def extract_pdfs_from_zip(self, project_id: int): project = Project.objects.get(pk=project_id) ... # Start unzipping from here. # NOTE: This script precludes that there's no MACOSX shenanigans in the zip file. pdf_file_pattern = re.compile(r'.*\.pdf') pdf_name_pattern = re.compile(r'.*\/(.*\.pdf)') with ZipFile(project.files) as zipfile: for name in zipfile.namelist(): # S2: Check if file is .pdf if pdf_file_pattern.match(name): pdf_name = pdf_name_pattern.match(name).group(1) print('Accessing {}...'.format(pdf_name)) # S3: Save file as a new Pdf entry new_pdf = Pdf.objects.create(name=pdf_name, project=project) new_pdf.file.save(ContentFile(zipfile.read(name)), pdf_name, save=True) # Problem here print('New document saved: {}'.format(new_pdf)) else: print('Not a PDF: {}'.format(name)) return 'Run complete, all PDFs uploaded.' For some reason though, the part where its saving the document is not outputting a PDF anymore. I … -
How can i get loop values from a python script so as to update progress bar?/
I have a python script which runs using ajax call and it takes some minutes time.So I want to display a progress bar for that.For that I want to know the loop values so as to update the progress bar.How can i achieve that? -
Celery tasks returning AsyncResult instead of Dictionary
I am facing the problem. I am using celery for an asynchronous task. When I run the worker (RabbitMQ), the shared_task run successfully but didn't return the result as expected. I want to return the dictionary when the shared_task runs but got this type of response. 249ccaf5-dae9-4296-b093-e0f09eff2632 My views.py where shared_task is running def request_twitter(request): global screenname access_key = request.session['access_key_tw'] access_token = request.session['access_secret_tw'] dic = requesting_twitter.delay(access_key,access_token,screenname) print(dic) return render(request,'info.html', dic) And my tasks.py file @shared_task def requesting_twitter(ackey,asecret,sc): CONSUMER_KEY = 'K9lD2i0feSrOtCBQVIjvrygce' CONSUMER_SECRET = '82HqosHNh4JD4NMruRjRZ4pLU5C1zf983tDzhHlEwuamaSPKGk' oauth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) access_key = ackey access_secret = asecret oauth.set_access_token(access_key, access_secret) api = tweepy.API(oauth) screenname = sc user = api.get_user(screenname) userTweet = api.user_timeline(screenname, count=1) for tweets in userTweet: most_recent_tweet = tweets.created_at try: sn = user.screen_name except: sn = '' try: disply_name = user.name except: disply_name = '' try: descriptin = user.description except: descriptin = '' try: locatin = user.location except: locatin = '' try: urll = user.url except: urll = '' try: Date_joined = user.created_at except: Date_joined = '' try: twitter_user_id = user.id except: twitter_user_id = '' try: profile_lang = user.lang except: profile_lang = '' try: time_zzone = user.time_zone except: time_zzone = '' try: tweetzz = user.statuses_count except: tweetzz = '' try: followingg = user.favourites_count except: … -
parse multiple sql output records(using cursor object) in django
In django, I used connections concept to fetch data. The output have multiple records need to parse through it. cursor = connections['configuration'].cursor() cursor.execute("SELECT DISTINCT(integrations.trail_userid),integrations.environment, integrations.endpoint, integrations.connectivity_status, integrations.subscription_status from integrations INNER JOIN list_integration_tools ON integrations.endpoint = list_integration_tools.endpoint WHERE integrations.`trail_username`='ambika02'") row = cursor.fetchall() print(row) This is my CODE Result of row is ((30, None, 'snow', 'production', 'dev'), (30, None, 'jira', 'production', 'production')) I need to parse through row to get all values row[0] gives me the first record (30, None, 'snow', 'production', 'dev'), But how do I parse through the first record -
AttributeError: 'NoneType' object has no attribute 'id'. This type of error is thrown
When i run the program it throw the follow error occurs: viewset def get_queryset(self): qs = self.queryset.filter(user_tenant__id=self.request.user.user_tenant.first().id).exclude( pk=self.request.user.id) Internal Server Error: /tenant-user/ Traceback (most recent call last): File "/home/surya/.local/share/virtualenvs/lutechbackend-TyCFyjgb/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/home/surya/.local/share/virtualenvs/lutechbackend-TyCFyjgb/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/surya/.local/share/virtualenvs/lutechbackend-TyCFyjgb/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/surya/.local/share/virtualenvs/lutechbackend-TyCFyjgb/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/surya/.local/share/virtualenvs/lutechbackend-TyCFyjgb/lib/python3.6/site-packages/rest_framework/viewsets.py", line 103, in view return self.dispatch(request, *args, **kwargs) File "/home/surya/.local/share/virtualenvs/lutechbackend-TyCFyjgb/lib/python3.6/site-packages/rest_framework/views.py", line 483, in dispatch response = self.handle_exception(exc) File "/home/surya/.local/share/virtualenvs/lutechbackend-TyCFyjgb/lib/python3.6/site-packages/rest_framework/views.py", line 443, in handle_exception self.raise_uncaught_exception(exc) File "/home/surya/.local/share/virtualenvs/lutechbackend-TyCFyjgb/lib/python3.6/site-packages/rest_framework/views.py", line 480, in dispatch response = handler(request, *args, **kwargs) File "/home/surya/.local/share/virtualenvs/lutechbackend-TyCFyjgb/lib/python3.6/site-packages/rest_framework/mixins.py", line 40, in list queryset = self.filter_queryset(self.get_queryset()) File "/home/surya/Desktop/lutechbackend/tenant/views/views.py", line 129, in get_queryset qs = self.queryset.filter(user_tenant__id=self.request.user.user_tenant.first().id).exclude( AttributeError: 'NoneType' object has no attribute 'id' [09/Apr/2019 03:50:49] "GET /tenant-user/ HTTP/1.1" 500 106741 How to solve this problem ?? -
I want to run machine learning algorithm using django but django is not taking csv file path
I am creating spam detection system in django in my application from homepage i will enter any string and that string will go to ml function and that function return either string is spam or ham and that result will print on next page but i am not able to define pata of csv file in pd.read_csv function. it is showing error '../data/spam.csv' does not exist: b'../data/spam.csv' view.py file def hompage(request): form = DetectForm(request.POST) return render(request, 'index.html', {'form': form}) def result(request): form=DetectForm(request.POST) if form.is_valid(): x=form.cleaned_data['msg'] y=machine(x) return render(request, 'result.html',{'msg':y}) ml.py file def machine(stringx): import pandas as pd import numpy as np import re from nltk.stem.porter import PorterStemmer from nltk.corpus import stopwords data = pd.read_csv('../data/spam.csv', encoding='latin-1') data = data.iloc[:, [0, 1]] data['v1'] = data.v1.map({'ham': 0, 'spam': 1}) courpas = [] # data_cleaning string = stringx df2 = pd.DataFrame({"v1": [0], "v2": [string]}) data = data.append(df2, ignore_index=True) # data_cleaning for a in data['v2']: review = re.sub('[^a-zA-Z]', ' ', a) review = review.lower() review = review.split() ps = PorterStemmer() review = [ps.stem(x) for x in review if not x in stopwords.words('english')] review = ' '.join(review) courpas.append(review) # create a bag of word model from sklearn.feature_extraction.text import CountVectorizer cv = CountVectorizer(max_features=5000) x = cv.fit_transform(courpas).toarray() y … -
Problem with Data Type in my Python/Django Code
I'm running into a noob issue with my code. It's a simple multiplier function working like as: 1/ A Model 1.a/ with 2 fields : name as CharField and price as Decimalfield 1.b/ with a method Multiplier that is basically newprice = self.price * arg 2/ A form to capture an input (the value to multiply self.price with) 3/ A view to pass the template with the form and the context I keep running into can't multiply sequence by non-int of type 'NoneType' or TypeError: unsupported operand type(s) errors. I tried updating the code to change the type of my object, or model fiels, etc but cannot find a working solution... btw : if the model method has its argument replaced by a constant, everything is working as it should Model class Product(models.Model): name = models.CharField(max_length=30) price = models.DecimalField(max_digits=5, decimal_places=2) def __str__(self): return self.sku def multi(self, n): np = self.price * n return np Form class Input(forms.Form): data = forms.DecimalField(max_digits=5, decimal_places=2) View from django.shortcuts import render from .models import Product from .forms import Input from decimal import Decimal def index(request): list = Product.objects.all() value = 1 if request.method == "POST": form = Input(request.POST or None) if form.is_valid(): value = request.POST.get('data') … -
How to Fix "Models aren't loaded yet" in Django
I am attempting to import data from a csv file into my Django model Move. It has worked previously but after deleting the database and changing some things something is causing an error to occur. My models aren't loaded yet apparently. I have attempted to find a solution but haven't encountered any. Models.py from django.db import models from django.utils.text import slugify import csv # Create your models here. class Move(models.Model): move_title = models.CharField(max_length=200) move_artist = models.ForeignKey('Artist', on_delete=models.CASCADE, null=True, blank=True) move_slug = models.SlugField(unique=True, max_length=250) def __str__(self): return self.move_title def save(self, *args, **kwargs): self.move_slug = slugify(self.move_title) super(Move, self).save(*args, **kwargs) with open("path/to/file/data.csv") as f: reader = csv.reader(f) for row in reader: _, created = Move.objects.get_or_create( move_title=row[0], move_artist=row[1], ) Error messages: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x106ba8510> Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/utils/autoreload.py", line 248, in raise_last_exception raise _exception[1] File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module return … -
Django self.assertEqual comparing 2 new unsaved objects
Lets say I have a CustomerProfile model class CustomerProfile(models.Model): billing_profile = models.ForeignKey(...) and when I run the assertEqual on 2 unsaved objects, it raises AssertionError self.assertEqual( CustomerProfile(billing_profile=default_profile), CustomerProfile(billing_profile=default_profile) ) Gives the following error: AssertionError: <CustomerProfile: Full Charge None> != <CustomerProfile: Full Charge None> I don't understand why because the instance id would not have been populated since it's unsaved. -
Django Query Filter syntax issue
I'm using Django 1.10.5 with python 3.6. I have the following model classes: class PublishedDetails(FillableModelWithLanguageVersion): user = models.ForeignKey(settings.AUTH_USER_MODEL) .... class PublishedRecordedActivity(models.Model): published_details = models.ForeignKey(PublishedDetails, null=False, blank=False, on_delete=models.CASCADE) timestamp_added = models.DateTimeField(auto_now_add=True) activity_type = models.IntegerField(null=False, blank=False, default=1) With a lot of assistance, I have a query that will return all the details for the activity type of 1: aggregated_type_1 = PublishedRecordedActivity.objects.filter( activity_type=1).annotate(month=TruncMonth('timestamp_added')).values( 'month').annotate(sum_by_month=Count('month')).order_by('-timestamp_added') However, I now want to only return the query for specific published details. For example where published_details=73, where the 73 is the id value in the model/table PublisheDetails. So I extended the query, but I'm receiving the error: 'publisheddetails__id' is not defined. I have imported the models to the view. Here is the offending query: aggregated_type_1 = PublishedRecordedActivity.objects.filter( activity_type=1, published_details=publisheddetails__id).annotate(month=TruncMonth('timestamp_added')).values( 'month').annotate(sum_by_month=Count('month')).order_by('-timestamp_added') I have tried back tracking and I have referenced the django docs, but the solution is escaping me. -
django-import-export how to handle GenericRelations?
I'm using django-import-export module to export the record. However, I couldn't export the generic relations. I just want to get all the details of GenericRelation. Found the snippet below in Github but it doesn't work. class DudeResource(resources.ModelResource): address = fields.Field( column_name='address', attribute='address', widget=widgets.ForeignKeyWidget(Address, 'name')) # use a unique field class Meta: model = Dude fields = ['address'] My Models Company |-- Name |--- Address(Generic Relation) Address |--content_type |--object_id |--content_object |--line_1 |--line_2 |--city |--country I just need to import/export line_1, line_2, city, and country. Can someone help me on this? Thanks! -
How can I enable new users choose a group when registering on my Django app?
I want to be able to add a group choice checkbox to my user creation form ( signup.html) ( forms.py) so that on registration they get assigned to the group they chose. these groups will have different permissions to access specific models on the site. thanks! -
Django channels 1.x authenticate user
I run a django server and am trying to create a channel for chatting. The client is a react-native application, with javascript backend. When the user connects to the server via websocket (ws_connect), I want to be able to perform an authentication check, to see if the user is already in the database and get who this user is. I use default django auth accounts (django.contrib.auth.models). For authenticating the http requests I use django.contrib.auth.decorators.login_required and from the client I send an Authorization Header with the JWT token. How should I do the same for websocket requests? The recommended chat consumer uses channels.auth.channel_session_user_from_http. Is this the correct way for what I want? And how can I send the user's credentials (or token) from the client so that the server can check them? I saw a relevant SO question and the relevant documentation, but could not solve my problem. Any help would be appreciated. django version: 1.11.20 django-channels version: 1.1.8 -
Django Cookiecutter Production Server Setup on DigitalOcean
I am trying to setup my Django Cookiecutter code on an Ubuntu server hosted on Digital Ocean. (My first attempt at such a thing.) It does not appear that my .env file is loading? DATABASE_URL=postgres://myapp:pwd123@127.0.0.1:5432/myapp DJANGO_ALLOWED_HOSTS=187.99.73.187,myapp.com,187.99.73.187:8000 DJANGO_ADMIN_URL=admin DJANGO_SETTINGS_MODULE=config.settings.production DJANGO_SECRET_KEY=A8fpfkN5}...m5~^jggSo3wq`0Z* I am using the latest version of Cookiecutter. https://github.com/pydanny/cookiecutter-django Do I have to do something special to activate/recognize this code? Right now I am getting an error of add '187.99.73.187' to ALLOWED_HOSTS. But it is in the env file. I also had Postgres error based on not getting data from this new .env file. I see instructions and videos for setting up Cookiecutter on Docker, Heroku and PythonAnywhere. Just not for a simple Linux installation. Thanks. -
How to parse output of .serialize('json', data) from Django in HTML
I'm trying to loop through a serialized JSON object and display it as a list, but instead of listing the attributes I want, the loop runs over each individual character in the JSON string. When I do the same with a list of dicts it works. What am I doing wrong? Ptyhon code: def menu(request): # This is the object that I want to parse dishes = Dish.objects.all() dishes_ser = serializers.serialize('json', dishes) # This list is copy-pasted directly from the output of the serialized query to see if I could get that to work check = [ {"model": "orders.dish", "pk": 1, "fields": {"dish": "Pizza"}}, {"model": "orders.dish", "pk": 3, "fields": {"dish": "Sub"}}, {"model": "orders.dish", "pk": 5, "fields": {"dish": "Pasta"}}, {"model": "orders.dish", "pk": 6, "fields": {"dish": "Salad"}}, {"model": "orders.dish", "pk": 7, "fields": {"dish": "Dinner platter"}} ] context = { 'dishes': dishes_ser, 'check': check, } return render(request, "menu.html",context) HTML {% extends "layout.html" %} {% block title %} Menu {% endblock %} {% block content %} <h1>Menu</h1> <a href="/">Home</a> Raw output of the check variable as received from Django: <br /> <br /> {{check}} <br/> <br/> <ul> {% for data in check %} <li>{{ data.fields.dish }}</li> {% empty %} <li>No Dishes</li> {% endfor %} … -
What is the rightway of importing and inheriting classes?
I am relatively new to programming. So far I have seen two ways that classes are imported and inherited in python. The first one which is also what I have been doing while learning Flask is: from package.module import SuperClass class SubClass(SuperClass): The other one which I am seeing quite often in most Django code is: from package import module class SubClass(module.SuperClass): Which one is the right way of doing things? Is there a significant advantage of using one over the other? -
Testing whether a Url is giving 500 error or not in Django
I want to test Urls whether am getting 500 error or not. In normal case where login is not required I get status_code 200 but where login is required, it gives me 302 error. So, how can one test loginrequired and paramterized url in best way. Thank You -
Python/Django for hotel managment system or Node/Express
Should i use node.js/express or python/django for hotel pms? Im about to start developing a hotel managment system, for arrives/departures, booking guests, housekeeping services, etc. I know how to program on both languages, although i have a little more experience in pyhton. I would really like to make this project in node but my concerns are about performance. I dont have experience in this kind of systems so i dont know if cpu-intensive is going to be a problem in the future. Is node.js a good choice for this kind of project or should i go with python?? -
Django QuerySet: Cannot resolve expression type, unknown output_field
I have a tree structure in postgres and I want to get number of nested nodes for visible nodes. You can look at the SQL query to get an idea. I am trying to implement following query in Django 1.11.20: select id, path, ( select count(*) from tree_node where path <@ t.path and not path <@ array( select path from tree_node where path <@ t.path and visibility_id = 0 ) ) as nested_nodes from tree_node t order by id; What I am trying: def annotate_visibile_nested_nodes_count(self): """ Get all nested nodes for current path except the hidden ones and their descendants """ from src.tree.models import Visibility invisible_nested_nodes_paths = self.model.objects.filter(path__descendantsof=OuterRef(OuterRef('path')))\ .filter(visibility_id=Visibility.HIDE)\ .values('path') visible_nested_nodes_count = self.model.objects.filter(path__descendantsof=OuterRef('path'))\ .exclude(path__descendantsin=Subquery(invisible_nested_nodes_paths))\ .annotate(count=Count('*'))\ .values('count')[:1] return self.annotate( nested_nodes=Subquery(visible_nested_nodes_count, output_field=IntegerField()) ) I am getting an error: File ".../django/db/models/expressions.py", line 237, in output_field raise FieldError("Cannot resolve expression type, unknown output_field") FieldError: Cannot resolve expression type, unknown output_field I can't figure out whether the error is coming from first annotate or the second one and how to fix it. Thanks in advance for your help. -
How to use multiple user models in Django?
I'm trying to use two user models with different 'username' type each one. First user type is an administrator who login in with username and password. Second, a customer who login with phone number and password. Only the customer has custom fields. I tried customize the Django User model but it only allows one auth user model. I am thinking use an authentication backend. Administrator only will login in admin dashboard, while customer only login in application. -
Foreign Key - get values
I have created the following models. Many Accounts belong to one Computer. class Computer(models.Model): name = models.CharField(max_length=256) def __str__(self): return str(self.name) class Accounts(models.Model): computer = models.ForeignKey(Computer, on_delete=models.CASCADE, related_name='related_name_accounts') username = models.CharField(max_length=10) def __str__(self): return str(self.username) I now want to create a Form where i can choose one user from a dropdown-list of all users that belong to a Computer class ComputerForm(forms.ModelForm): class Meta: model = Computer exclude = ['name',] def __init__(self, *args, **kwargs): super(ComputerForm, self).__init__(*args, **kwargs) self.fields['user']=forms.ModelChoiceField(queryset=Computer.related_name_accounts.all()) But i get an error 'ReverseManyToOneDescriptor' object has no attribute 'all' How do i have to adjust the queryset in __init__ to display all users of a computer? -
How to create a series of buttons in JavaScript which can be clicked to do different versions of the same function?
I am making a website with Django to provide students with a spelling test which they fill out and then receive a mark out of 10. The students cannot be allowed to see the words so I have given them a series of sound bytes using the function 'speak()', only when I press the buttons they all say the same thing because I don't know how to parse the individual data to the function to tell it which spelling to "speak". I know that the reason why it isn't working is because I'm parsing "sBite.id" to the speak() function, and sBite.id will always be the same value. I just don't know what value I should parse in order to send the correct spelling to the function Here is the relevant JS code: function speak(word){ var msg = new SpeechSynthesisUtterance(usedWords[word]); window.speechSynthesis.speak(msg); } usedWords=[]; function load(played, mistake, score){ alert(mistake) var x =["ball","racket","apple","cheese","find","any","new", "display","please","happy","plead","pleat","aple","bple","cple"]; var step; var spellList = document.getElementById("spellList"); if(listlen < 10){ for(step = 0;step < 10;step++){ li = document.createElement("li"); sBite = document.createElement("button"); rand = x[Math.floor(Math.random() * x.length)]; if(usedWords.includes(rand)){ step = step - 1; continue; } else{ usedWords.push(rand); li.appendChild(document.createTextNode(rand)); li.id = "spelling"; spellList.appendChild(li); var testy = usedWords[step]; sBite.setAttribute("onClick","speak(sbite.id)"); sBite.type="button"; sBite.id=step; sBite.textContent=sBite.id; spellList.appendChild(sBite); … -
Django Rest Framework: File upload request header and webkit boundary included in saved file using FileUploadParser
I'm currently trying to build out a an application with both client-side and server-side code. My frontend is built in React, with my backend being Python/Django, utilizing django-rest-framework. The feature I'm building out now is a file-upload feature, which utilizes the Dropzone.js library in order to save and store files on the server. Eventually I'd like to be routing the files to AWS S3, but I'm not quite there yet. My views.py file is currently accepting and saving the file, however the webKitBoundary and file information are also being saved in the file. Optimally, I'd like to be saving the file without having to do file manipulation in order to trim out the unnecessary information. Here's my views.py: class SaveFile(APIView): authentication_classes = (CsrfExemptJWTAuthentication, ) parser_classes = (FileUploadParser, ) def post(self, request, format=None): newFile = File() newFile.file = request.data['file'] newFile.save() return HttpResponse('file upload success') My file model: class File(models.Model): file = models.FileField(upload_to = 'files') def __str__(self): return self.file.name class Meta: db_table = "files" My test.txt: hello (.^-^), And the saved result: ------WebKitFormBoundaryySdQAcRrBj8kluZ5 Content-Disposition: form-data; name="file"; filename="yurrr.txt" Content-Type: text/plain hello (.^-^), ------WebKitFormBoundaryySdQAcRrBj8kluZ5-- I've found a similar question here: headers and boundary included in uploaded file django rest framework However when I try …