Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to merge Multiple URL's in a Single URL in Django?
I ahve multiple url's for sitemap in my website, but I want to merge all sitemap url's with a single url, I create different-2 sitemap according to my requirement, but now i want to display all those urls in a single url, Here is my urls.py file.. path('sitemap/sitemapblog.xml', sitemap, {'sitemaps': sitemapblog}), path('sitemap/sitemapproject.xml', sitemap, {'sitemaps': sitemapproject}), path('sitemap/sitemaplocation.xml', sitemap, {'sitemaps': sitemaplocation}), path('sitemap/sitemaplocality.xml', sitemap, {'sitemaps': sitemaplocality}), path('sitemap/sitemapbuilder.xml', sitemap, {'sitemaps': sitemapbuilder}), path('sitemap/sitemapcategory.xml', sitemap, {'sitemaps': sitemapcategory}), path('sitemap/sitemapsearchtag.xml', sitemap, {'sitemaps': sitemapsearchtag}), I want to merge these all url's in a single url... path('sitemap.xml', sitemap, {'sitemaps': sitemapblog, 'sitemaps': sitemapproject, 'sitemaps': sitemaplocation}), i want to merge in above sitemap.xml file... i have done as this, but I examplae.com/sitemap.xml is displaying sitemap/sitemaplocation.xml this sitemap data, please let me know how i can display only above urls in sitemap.xml. -
How do I generate a message in a User Edit View using Django
I am trying to generate a message when someone edits their user profile. The code that I have created is below. The profile gets updated and returns me to my home page, but doesn't generate a message. Please help. Thanks. base.html {% if messages %} {% for message in messages %} {{ message }}<br/> {% endfor %} {% endif %} views.py from django.contrib import messages class UserEditView(generic.UpdateView): form_class = EditProfileForm template_name = 'registration/edit_profile.html' success_url = reverse_lazy('home') def get_object(self): return self.request.user def get_success_message(self): msg = 'Profile has been updated!' messages.add_message(self.request, messages.INFO, msg) -
Django Joining Tables
I am trying to get the information from one table filtered by information from another table (I believe this is called joining tables). I have these two models: class Listing(models.Model): title = models.CharField(max_length=64) description = models.CharField(max_length=500) price = models.DecimalField(max_digits=11, decimal_places=2, validators=[MinValueValidator(Decimal('0.01'))]) category = models.ForeignKey(Category, on_delete=models.CASCADE, default="") imageURL = models.URLField(blank=True, max_length=500) creator = models.ForeignKey(User, on_delete=models.CASCADE, related_name="creator", default="") isOpen = models.BooleanField(default=True) def __str__(self): return f"{self.id} | {self.creator} | {self.title} | {self.price}" class Watchlist(models.Model): listing = models.ForeignKey(Listing, on_delete=models.CASCADE, related_name="listingWatched", default="") user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="userWatching", default="") What I need to do is to get all the listings from a specific user Watchlist, the idea is to generate a page with all of the information of each of the listings that are in the user's watchlist. What should I do? Thanks in advance! -
Need to display data from mysql into a table in a modal using django
I am creating a web app which has several buttons which has different functions. When a button is pressed I need to display data (a users data table from mysql database) into a modal without reloading the page. I have used django along bootstrap for building my webapp.Here is my code views.py from django.shortcuts import render, redirect from django.db import connection import datetime from django.contrib import messages def edit_parameter_view(req): #Some_code_here def create_user_view(req): #Some_code_here def show_users_view(req): brcd=req.session['brcd'] with connection.cursor() as cursor: cursor.execute("SELECT * from gl.users WHERE brcd=%s" % (brcd)) data = cursor.fetchone() return render(req, 'edit_parameter.html',{'data':data}) The data here is the table which has the various attributes of the user such as username,userid,password,addres,etc. I need this table to show in moadal of my webpage. edit_parameter.htm {% load static %} <!DOCTYPE html> <meta content="width=device-width, initial-scale=1.0" name="viewport"/> <html lang="en"> <head> <meta charset="UTF-8"> <meta content="IE=edge" http-equiv="X-UA-Compatible"> <meta content="width=device-width, initial-scale=1" name="viewport"> {%block title %} <title>Success</title> {% endblock %} <link crossorigin="anonymous" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" rel="stylesheet"> <style> #css </style> {% block content %} <form action="{% url 'update' %}" method="post"> {% csrf_token %} <table BORDER=0 style="float: left; margin-top:1px; margin-left:30px;"> #table </table> <table> <td><button type="button" class="btn btn-danger custom" onclick="this.form.action='{% url ' create_user' %}';this.form.submit();">Add New User</button></td> <td><button type="button" class="btn btn-danger custom" onclick="this.form.action='{% … -
Converting Django from SQLite to PostgreSQL
I'm new to Python and Django. I've purchased a book, Django 3 by example (3rd Edition) and really enjoying the lessons. I'm in chapter 3 now and the goal is to enhance the search engine functionality. In order to do so, the book has steps to convert the DB to PostgreSQL. I'm following the directions below and I've tried several things to fix the issue that I've found on Google. I can't seem to find the answer. Steps: install PostgreSQL: sudo apt-get install postgresql postgresql-contrib install psycopg2: pip install psycopg2-binary==2.8.4 create user for PostgreSQL database. Open the shell and run the following commands. a) su postgres b) createuser -dP blog Enter a password for the new user and then create the blog database and give ownership to the blog user you just created with the following command: createdb -E utf8 -U blog blog Edit the settings.py file... steps omitted. I'm stuck on step 3a above. I get asked for a password for postgres and nothing seems to work. I have tried some things found on google as well. Here is what I've tried. sudo -u postgres psql \password postgres enter and confirm password \q Try to log back in using … -
I am trying to inject an already rendered Django template into a section of my page using AJAX
I am following by this tutorial on how to get live updates on django without refreshing the page. The tutorial uses flasks render_template to get the html rendered which is then injected to a page section. I am trying to do the same in Django, But django just directly renders it in the browser... I don't want that. I just want django to send the rendered html response to AJAX which could then inject that to a section on my live page. Here is the code : views.py class ManageView(LoginRequiredMixin, View): template_name = "dashboard/manage.html" context = {} def get(self, request, app_id, folder_id=None): app = App.objects.get(pk=int(app_id)) self.context["app"] = app if folder_id: try: self.context["folder"] = Folder.objects.get(id=folder_id) except: self.context["folder"] = app.folder else: self.context["folder"] = app.folder return render(request, self.template_name, self.context) def post(self, request, app_id, folder_id=None): try: files = request.FILES.getlist('files_to_upload') folder_name = request.POST.get("folder") master = request.POST.get("master") if master: master = Folder.objects.get(id=master) if folder_name: Folder.objects.create(name=folder_name, owner=request.user.customer, folder=master) if files: for file in files: if file.size < settings.MAX_FILE_SIZE: File.objects.create(folder=master, item=file, name=file.name, size=file.size) app = App.objects.get(pk=int(app_id)) self.context["app"] = app if folder_id: try: self.context["folder"] = Folder.objects.get(id=folder_id) except: self.context["folder"] = app.folder else: self.context["folder"] = app.folder return render(request, 'dashboard/filesection.html', self.context) except DatabaseError: return render(request, "dashboard/index.html", self.context) urls.py urlpatterns = [ url(r'^manage/(?P<app_id>[0-9]+)/(?P<folder_id>.+)', … -
Can't pip install django-dash
I have django and dash installed but not django-dash. Any ideas why this wont work? I've tried both: pip install django_plotly_dash pip install django-dash Command Prompt Error: ERROR: Could not find a version that satisfies the requirement django_plotly_dash (from versions: none) ERROR: No matching distribution found for django_plotly_dash -
In django, how do I post multiple models of the same type?
I am trying to create an app that keeps track of who took out our dogs last and what each dog did. I have set my models up so that the actual post contains who took them out last, when they took them out, and any issues that they had (if any). The other model, Actions, uses both the Post and Dog models as a foreign keys to identify what each dog did when they were taken. The issue that I am currently facing is when I attempt to make a post, The actions that I select repeat even if I didn't check them off (i.e. Dog_1 peed and Dog_2 did nothing but when posted it shows both dogs peed). I believe the issue stems when the post form page is rendered, each instance of the Action_Form is copied, which causes the fields' ids to be the same. How can I fix this? models.py: from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Dog(models.Model): name = models.CharField(max_length = 20) class Post(models.Model): walker = models.ForeignKey(User, on_delete = models.CASCADE) time_posted = models.DateTimeField(default = timezone.now) issues = models.TextField(max_length = 300) class Action(models.Model): post = models.ForeignKey(Post, on_delete = models.CASCADE) dog … -
Django Multilangual Site
Hello guys i want to make an multilangual site but i don't have any idea how to do and i've some questions. First of all, after i finish my project i did a second template(for second lang) for every template. Then i change my idea and deleted secend templates and make one template for each page with using 7 or 8 if-elif-endif. Now i'm really confused about what to do. Does my first try was good and faster or my second is good and faster. And i've a idea but i don't know is it possible. I want to make 1 template for each page and also at the back end i want to create dictionary(?) like this: en-fr-tr hello-bonjour-merhaba as a, goodbye-aurevoir-hoscakal as b and at the templates i just want to write {{dictionary.a}} or {{dictionary.b}}. For final i hope you can understand my english and before finishing i want to add i'm not 100% sure the meaning of the 'template', when i'm saying template i mean .html docs (like index.html and product.html is an template) -
Redux-persist: persist callback not updating axios interceptors
Greeting! i have Django/React app with JWT authentication, and i need to update axios interceptors with the proper headers after my store is rehydrated. the issue that i have, the logic outside of interceptors works, but the one within does not. // store.js const store = configureStore({ ... }) let persistor = persistStore(store, { manualPersist: false }, () => { return authorizationProvider(store); }); // apiCaller.js const apiCaller = axios.create({ baseURL: 'http://localhost:8000/api/', timeout: 10000, timeoutErrorMessage: "request took too long", xsrfCookieName: 'csrftoken', xsrfHeaderName: 'X-CSRFTOKEN', withCredentials: true, }); export default apiCaller; //interceptor.js const authorizationProvider = (store) => { const { auth } = store.getState(); console.log(auth) // works with rehydated values apiCaller.interceptors.request.use( config => console.log(config) // doesn't work at all ); } // index.js ReactDOM.render( <Provider store={store}> <PersistGate persistor={persistor} loading={<LinearProgress variant={'indeterminate'} color={"primary"} />}> <App /> </PersistGate> </Provider>, document.getElementById('root') ); Extra i have tried to call authorizationProvider(store) in index.js but it does not use the rehydrated values i have tried to call the same function from App.js and it raised undefined errors Appreciate your help ! -
Cannot add "simplejwt.token_blacklist" to install apps
Hi I'm having an issue with restframework_simplejwt library. When I add blacklisting to installed apps ir returns me an error. settings.py file: INSTALLED_APPS = [ ... 'rest_framework_simplejwt.token_blacklist', ... ] error: django.db.utils.ProgrammingError: relation "token_blacklist_outstandingtoken" does not exist LINE 1: INSERT INTO "token_blacklist_outstandingtoken" ("user_id", "... -
Does a Django production server on Digital Ocean require a SSL certificate in order to download images from Digital Ocean Spaces?
My attempts to download an uploaded image from my created "Spaces" on Digital Ocean works from my local Django server but not from my production Django server on digital ocean. Earlier i received a SSL ERROR on my local server which i managed to get passed with the code below. url = 'https://my-spaces.ams3.digitaloceanspaces.com/my-spaces-static/images/XXXXXXXXX.png' ssl._create_default_https_context = ssl._create_unverified_context resp = urllib.request.urlopen(imageurl) My production Django server shows as "not secure". Do i need to create a SSL certificate somehow to my production server on Digital Ocean so that users can download images from "Spaces"? -
Prevent hitting the database for specific field in django admin
I am running a django app and want to customize the admin panel for a specific model. Concretely, I want to exclude a specific model field from being loaded when I list all instances. The field I want to exclude is a JSONB-field and the dataload is extremely heavy. So loading many objects breaks the server. I already paginated the model and I am excluding the field to not be displayed. Yet, it still loads the data from the field as my server is still breaking. Here is what I am doing which works but still hits the DB: My model class HeavyLoad(models.Model): description = models.CharField(...) data_json = JSONField( help_text="Data for heavy load" ) My admin model class HeavyLoadAdmin(admin.ModelAdmin): fields = ('description', ) exclude = ['heavy_data'] model = HeavyLoad list_per_page = 5 search_fields = [field.name for field in Heav.HeavyLoad.get_fields()] It would be enough for me if the admin panel only loads the description from the DB and shows it in the panel. I guess in SQL this would be sth like SELECT description FROM heavyload; But where could I overwrite a behaviour like this? Or is there a setting that I am not aware of that handles this for me? … -
Heroku python application getting continuous requests from "Typhoeus"
I am hosting a python application on heroku, that hosts a react JS project. The react JS project is built, and served by the django python backend. I am using a free dyno and don't use it often, but I see that my hourly usage is extremely high, and going into the logs I see requests continuously. 2020-12-23T08:02:00.180380+00:00 app[web.1]: 10.63.103.37 - - [23/Dec/2020:08:02:00 +0000] "GET / HTTP/1.1" 200 2301 "-" "Typhoeus - https://github.com/typhoeus/typhoeus" 2020-12-23T08:02:00.180822+00:00 heroku[router]: at=info method=GET path="/" host=x.herokuapp.com request_id=33b084b4-b327-491f-8d55-5cd453cef588 fwd="34.235.149.12" dyno=web.1 connect=0ms service=516ms status=200 bytes=2661 protocol=http 2020-12-23T08:30:54.707583+00:00 app[web.1]: 10.69.161.99 - - [23/Dec/2020:08:30:54 +0000] "GET / HTTP/1.1" 200 2301 "-" "Typhoeus - https://github.com/typhoeus/typhoeus" 2020-12-23T08:30:54.709612+00:00 heroku[router]: at=info method=GET path="/" host=x.herokuapp.com request_id=7ff7fdca-c311-48a4-b66e-ee3218152c15 fwd="107.23.6.238" dyno=web.1 connect=2ms service=5ms status=200 bytes=2661 protocol=http It is causing my dyno to be awake quite often, and I can't figure out where/how these requests are happening. Any info here is greatly appreciated. -
nginx + uwsgi + django open uwsgi_params failed (13: permission denied)
I tried to follow the nginx document here https://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html. But stuck at Configure nginx for your site. I restarted nginx and it said "nginx: [emerg] open() "/home/hanys/oligoweb/uwsgi_params" failed (13: Permission denied) in /etc/nginx/sites-enabled/oligoweb.conf:19". My site.ini: [uwsgi] chdir = /home/hanys/oligoweb/ module = oligoweb.wsgi home = /home/hanys/.virtualenv/oligo-env master = true processes = 10 socket = /home/hanys/oligoweb/oligoweb.sock chmod-socket = 666 vacuum = true daemonize = /home/hanys/uwsgi-emperor.log uid = www-data gid = www-data my site.conf in /etc/nginx/sites-available/ upstream django { server unix:///home/hanys/oligoweb/oligoweb.sock; } server { listen 80; server_name IP address here; charset utf-8; # max upload size client_max_body_size 75M; # Django media and static files location /static { alias /home/hanys/oligoweb/static; } # Send all non-media requests to the Django server. location / { uwsgi_pass django; include /home/hanys/oligoweb/uwsgi_params; } } uwsgi_params has 664 permission. I tried chmod 777 uwsgi_params but it didnt work. Any help will be appreciated! -
Can't load static files in my django project, error 404
I'm new to Django and i've seen a lot of people asking about this particular problem but i followed every instruction i could find and it still doesn't work. My directorys look like this: /Peperina /Writing /statics/writing /css /scss /js forms.js /templates/writing forms.html my setings.py: import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) (...) INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'writing.apps.WritingConfig', ] (...) STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] STATIC_URL = '/statics/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'statics'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') My urls.py: (...) from django.conf import settings from django.conf.urls.static import static urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) finaly my forms.html (...) {% load static %} <script src="{% static 'writing\js\forms.js' %}"></script> yet 404 keeps showing up -
Django 'GET' request error 500 strict-origin-when-cross-origin
My django API needs to handle from partners 'POST' and 'GET' request. Everything is fine when partners server sends 'POST' but when on 'GET' i've got an error. Here is what i found in Chrome Network inspektor Request Method: GET Status Code: 500 Remote Address: someadress:80 Referrer Policy: strict-origin-when-cross-origin i've tested 'GET' by Postman and it works fine, i've installed and setup django-cors-headers. P.S. On sandbox partners server it worked fine, but on live i've got this error. Thanks a lot! -
Installation of GDAL on MacOS Catalina is failing
I'm trying to install GDAL on my mac (Catalina 10.15.7) using brew: brew install gdal but I'm running into an error that I don't understand: ==> Pouring glib-2.66.4.catalina.bottle.tar.gz cp: utimes: /usr/local/Cellar/glib/.: Operation not permitted cp: chmod: /usr/local/Cellar/glib/.: Operation not permitted Error: Failure while executing; `cp -pR /var/folders/7f/r7941wjd1fj2zlm79hwzlkcc0000gn/T/d20201223-26491-1643kjj/glib/. /usr/local/Cellar/glib` exited with 1. Here's the output: cp: utimes: /usr/local/Cellar/glib/.: Operation not permitted cp: chmod: /usr/local/Cellar/glib/.: Operation not permitted Warning: Bottle installation failed: building from source. ==> Patching Error: An exception occurred within a child process: Errno::ENOENT: No such file or directory @ rb_sysopen - /Users/<my_username>/Library/Caches/Homebrew/downloads/54f3f612bdfc9bfc09633176c7673816fe2a2188e470bf48d60d826bdf6bf21a--hardcoded-paths.diff I've also tried the following: brew install --build-from-source gdal But I run into the exact same error. I don't really understand what's the problem, though it seems to be related to permissions. I need some help on what I should do to resolve it. -
django.template.exceptions.TemplateDoesNotExist:/hello/
I created a function hello>view.py def index (request): return render(request,"hello/index.html") and an HTML file in hello>template>hello>index.html, but the is what I've got Internal Server Error: /hello/ Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/douju/lecture3/hello/views.py", line 7, in index return render(request,"hello/index.html") File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/template/loader.py", line 61, in render_to_string template = get_template(template_name, using=using) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/template/loader.py", line 19, in get_template raise TemplateDoesNotExist(template_name, chain=chain) django.template.exceptions.TemplateDoesNotExist: hello/index.html -
How to return data in Django model from database
I'm trying to return the data from the database in the Django model. Actually, I'm using my own encryption technique. So, I'm encrypting the data in save view in the model. The project is very big. I have a manual method. But I'm trying if there is any built-in model view like save in Django model to return all the fields data and to decrypt as well in the model. Here is my code. class TestModel(models.Model): testingText1 = models.CharField(null=True, blank=True,max_length=1000) testingText2 = models.CharField(null=True, blank=True,max_length=1000) def save(self,*args,**kwargs): self.testingText1 = encrypt(self.testingText1) self.testingText2 = encrypt(self.testingText2) super(TestModel, self).save(*args,**kwargs) Thanks in advance for any help. -
Problems with Django/Apache setup
I'm trying to host my personal website using Django WSGI deployment on Apache, but I'm getting the following error: AH01276: Cannot serve directory /var/www/django/: No matching DirectoryIndex My Django project folder is /var/www/django <VirtualHost *:80> ServerAdmin root@educorreia932.dev ServerName educorreia932.dev ServerAlias www.educorreia932.dev DocumentRoot /var/www/django ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /var/www/django/static <Directory /var/www/django/static> Require all granted </Directory> <Directory /var/www/django/website> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess django python-path=/var/www/django/ python-home=/var/www/django/venv WSGIProcessGroup django WSGIScriptAlias / /var/www/django/website/wsgi.py RewriteEngine on RewriteCond %{SERVER_NAME} =www.educorreia932.dev [OR] RewriteCond %{SERVER_NAME} =educorreia932.dev RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent] </VirtualHost> -
django html editor to add image in CharField form
I m using Django-wiki which use // markItUp! Universal MarkUp Engine, JQuery plugin in article form But in Django-wiki form used for create or edit articles I don't see how to add an image like in stack overflow So I would like to create a JS code to add image as in stack overflow. My question is: how to create that code (is stack overflow code is open source?) and secondly ho can I save image in my Django App? thanks for any link to help -
passing csrf_token through dynamically-generated form
I have a reddit-style threaded messageboard app which includes the functionality to reply in-line to comments via a separate javascript function. In the template file there is a link after each post: <a href="{% url 'posts:comment' post_id=post.id %}" onclick="quick_reply(this, '{% url 'posts:comment' post_id=post.id %}'); return false;">reply</a> The quick_reply function that generates the form is in a self-contained javascript file: function quick_reply(element, formURL){ ... quickReplyForm.innerHTML = ... "<div class=\"quick-reply-wrapper\">"+ "<form method=\"post\" action=\""+formURL+"\">"+ "<label for=\"id_subject\">Subject</label><input type=\"text\" class=\"subject\" name=\"subject\" id=\"id_subject\" maxlength=\"100\"/><br/>"+ "<label for=\"id_body\">Body</label><textarea name=\"body\" id=\"id_body\"></textarea><br/>"+ "<input type=\"submit\" value=\"Submit\" class=\"submit\"/>"+ "<input type=\"button\" value=\"Never mind...\" class=\"button\" onclick=\"quickReplyTransition.toggle();\"/>"+ "</form>"+ "</div>"; ... } (for clarity I have removed the other code from that function which is just dealing with visual effects) At the moment submitting the contents of the form generates a 'CSRF verification failed' error - but how can I pass through the csrf token from the template so that it can be placed in the dynamically-generated form? I can see that one answer would be to include the javascript function within the template file itself and add the form field there, but I would prefer to keep this in a separate javascript file in the static app if at all possible. Can this be done? … -
add images in a Django form CharField
I'm working on a wiki site with Django-wiki. When I want to create a new article, my issue is that I cannot copy paste an image in charfield. If I use drag and drop, the path is add to my CharField but not the image. I want to do like in Wikipedia having text and image in the article. Code is like this: create_article"html <form method="POST" class="form-horizontal"> {% wiki_form form %} <div class="form-group form-actions"> <div class="col-lg-2"></div> <div class="col-lg-10"> <button type="submit" name="save_changes" class="btn btn-primary btn-lg"> {% trans "Create root" %} &raquo; </button> </div> </div> </form> form is like this in Django-wiki: class CreateRootForm(forms.Form): title = forms.CharField( label=_("Title"), help_text=_( "Initial title of the article. May be overridden with revision titles." ), ) content = forms.CharField( label=_("Type in some contents"), help_text=_( "This is just the initial contents of your article. After creating it, you can use more complex features like adding plugins, meta data, related articles etc..." ), required=False, widget=getEditor().get_widget(), ) # @UndefinedVariable and model is -
can't adapt type 'InMemoryUploadedFile' in S3DirectField Django
I'm trying to store images in s3 of AWS and I got the error. I'm using postman to post data. Body is format data and header is multipart/form-data. I'm following these two tutorial. https://simpleisbetterthancomplex.com/tutorial/2017/08/01/how-to-setup-amazon-s3-in-a-django-project.html https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html setting.py INSTALLED_APPS = [ 'storages', 's3direct', ... ] AWS_ACCESS_KEY_ID = '*****' AWS_SECRET_ACCESS_KEY = '****' AWS_STORAGE_BUCKET_NAME = 'example-storage' AWS_S3_REGION_NAME = 'us-east-2' AWS_S3_ENDPOINT_URL = 'https://s3.us-east-2.amazonaws.com' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'static' S3DIRECT_DESTINATIONS = { 'primary_destination': { 'key': 'images/', 'allowed': ['image/jpg', 'image/jpeg', 'image/png'], }, } STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "s3:GetObject", "s3:PutObject", "s3:PutObjectAcl", "s3:ListMultipartUploadParts", "s3:AbortMultipartUpload" ], "Resource": "arn:aws:s3:::speakup-image-storage/*" } ] } urls.py urlpatterns = [ path('s3direct/', include('s3direct.urls')), ... ] models.py class Image(models.Model): image = S3DirectField(dest='primary_destination', blank=True) default = models.BooleanField(default=False) width = models.FloatField(default=100, null=True) length = models.FloatField(default=100, null=True) album = models.ForeignKey(Profile, related_name='images', on_delete=models.CASCADE) def __str__(self): return '{}'.format(self.image) My s3 has the folder called images and CORS is like this [ { "AllowedHeaders": [ "*" ], "AllowedMethods": [ "POST", "GET", "PUT" ], "AllowedOrigins": [ "*" ], "ExposeHeaders": [] } ] Do I miss something or Did I add something too mach? If you need views.py …