Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ImageField Model: Get file path on upload_to callable
I have a Django admin field for uploading images, in my model I'm using a callable to get the FileField instance and Filename. My goal is to open the file the user is trying to upload and upload it to my Dropbox account through their API and return the URL where the image is saved. How do I get the full path for the file being uploaded? Here is what I currently have in my model: def upload_to_dropbox(self, filename): return DropboxStorage.store_file(self.image, filename) image = models.ImageField(upload_to=upload_to_dropbox) I tried using the ImageField's .url property but that returns my MEDIA_ROOT path, maybe I'm going about this the wrong way? -
nginx config : for websocket(django channels)
I'm using google Compute engine VM instance(OS : Ubuntu 16.04) I've tried to deploy django app using channels. andrewgodwin's multichat app. url I installed nginx and below is my config. 1) $ vim /etc/nginx/nginx.conf user nginx; worker_processes 1; error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; events { worker_connections 1024; } http { include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; #tcp_nopush on; keepalive_timeout 65; #gzip on; include /etc/nginx/conf.d/*.conf; } 2) $ vim /etc/nginx/conf.d/default.conf server { listen 8000; server_name localhost; charset utf-8; #access_log /var/log/nginx/host.access.log main; location /stream { proxy_pass http://127.0.0.1:8443; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } location /static { alias /home/juhyun1849/Django/channels-examples/multichat/staticfiles; } location /media { alias /home/juhyun1849/Django/channels-examples/multichat/media; } location / { uwsgi_pass unix:/tmp/worker.sock; include uwsgi_params; } } 3) this is client side. <script> $(function () { // Correctly decide between ws:// and wss:// var ws_path = ("ws://" + window.location.host + "/stream"); console.log("Connecting to " + "/stream!"); var socket = new ReconnectingWebSocket(ws_path); socket.onopen = function () { ... }; socket.onmessage = function () { ... }; socket.onclose = function () { ... }; }; </script> 4) $ multichat/settings.py CHANNEL_LAYERS = { "default": { # This example … -
Jinja not executing HTML in Django Web Application: RuntimeError
I have created a web application called 'My_Website.' Inside this web application, there is a directory called 'My_Website'. In this directory, is the settings.py file, where I have already installed the Application I am using, called 'Home.' In my settings.py file (PycharmProjects/My_Website/My_Website/settings.py): INSTALLED_APPS = ( 'Home', 'Register', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ) This is just the INSTALLED_APPS tuple. There is more in the file. In the directory PycharmProjects/My_Website/My_Website/urls.py, I have the following: from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^Home/', include('Home.urls')) ] In the directory PycharmProjects/My_Website/Home/urls.py, I have the following: from django.conf.urls import url, include urlpatterns = [ url(r'^$', include('Home.urls')) ] Now, I am using Jinja templates, in the directory PycharmProjects/My_Website/Home/templates/home/ In this home directory there are 2 files: header.html and home.html header.html file: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div> {% block content %} {% endblock %} </div> </body> </html> home.html file: {% extends "home/header.html" %} {% block content %} <p>Hey!</p> {% endblock %} Here comes the problem. I am running this Web application in my localhost:8000 (Port 8000), and when I try to enter, it will not load the tag, and it gives me an … -
Distinguish API call from own app/webapp vs server
I am using Django and we are planning on opening some of our API for 3rd party usage. Till now we have been using DRF along with session authentication for our Django Web App and DRF with JWT for our Android application. What I would like to know is whether the call is from our own app (webapp/android app) or from 3rd party apps (they can call from their own applications, which can be other webapps/phone apps). Is there any way this can be distinguished? We want to count the no.of 3rd party API call to our server. -
admin page showing error in django
TypeError at /admin/student/user/ coercing to Unicode: need string or buffer, tuple found Any idea what's it about? admin.py from django.contrib import admin from .models import user class userAdmin(admin.ModelAdmin): fieldsets=[ (None,{'fields':['uid']}), (None,{'fields':['uname']}), (None,{'fields':['email']}), (None,{'fields':['password']}), ] admin.site.register(user,userAdmin) -
Django: Common/Reusable ModelAdmin Class
I have some functions like: has_delete_permission, has_add_permission, get_actions, formfield_for_foreignkey get_queryset Etc are the built-in ModelAdmin functions which I am using in almost all the ModelsAdmin's in my project. How to create a common/reusable class which include these functions and reuse in the other ModelAdmin classes? How to pass the reference of the Model or the ModelAdmin class to the common class? What should be the file structure to be maintained, in case this has to be used for many apps in a project. Some direction will be great help. Thanks. -
Changing session variable after views are rendered Django
I have two session variables that are required to be altered after rendering.When I try the following- def my_view(request) rend= render(request,"chat_page.html",{"answer":questions[request.session["stage"]]["instruction"]}) request.session["stage"]=request.session["stage"]+1 return rend I observe that first stagevariable is modified and then rendering is done.Is there a way that I can change value of stage after rendering is done. -
Django tests failing when run with all test cases
I have a problem with tests. When I run some tests I launch separately, they pass. When all together then fail. @mock.patch( 'apps.abstract.validators.years_range_is_not_future', new=fake_years_range_is_not_future ) def test_create_building_with_validation_of_foundation_period(self): self.c.login(username=self.user.username, password='111') response = self.c.post( '/en/api/buildings/', data={ 'name': "New Building", 'foundation_period': { 'lower': MIN_INT_VALUE, 'upper': MAX_INT_VALUE }, 'stream': { 'uuid': s_uuid(self.stream) } } ) self.assertEqual(response.status_code, status.HTTP_201_CREATED) I read about this problem here why would a django test fail only when the full test suite is run? and tried to patch the validator in the serializer file as shown here @mock.patch( 'apps.buildings.api.serializers.years_range_is_not_future', new=fake_years_range_is_not_future ) def test_create_building_with_validation_of_foundation_period(self): .............................................................. but then I get an incomprehensible for me exception Error Traceback (most recent call last): File "/usr/lib/python3.5/unittest/mock.py", line 1049, in _dot_lookup return getattr(thing, comp) AttributeError: module 'apps.buildings.api' has no attribute 'serializers' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3.5/unittest/mock.py", line 1149, in patched arg = patching.__enter__() File "/usr/lib/python3.5/unittest/mock.py", line 1205, in __enter__ self.target = self.getter() File "/usr/lib/python3.5/unittest/mock.py", line 1375, in <lambda> getter = lambda: _importer(target) File "/usr/lib/python3.5/unittest/mock.py", line 1062, in _importer thing = _dot_lookup(thing, comp, import_path) File "/usr/lib/python3.5/unittest/mock.py", line 1051, in _dot_lookup __import__(import_path) File "/home/env/project/apps/buildings/api/serializers.py", line 12, in <module> from apps.communities.api.serializers import CommunityBriefSerializer File "/home/env/project/apps/communities/api/serializers.py", line 297, in <module> … -
How to update a client-side page without js and jquery on django?
It is necessary to make a static application that uses a constant connection to the server to receive messages or updates the page in a period of time. With Django, python 2.7 and without js and jquery. -
django channels, celery and sockets: debug why data not sending
I need to send data via sockets so a user can get live update of the status of a background process. Here's a video of a simple working version: https://youtu.be/3561_VqQzRg (can provide code) and mine which works all the way till live feed where it fails: https://youtu.be/7FDaLkCRHpw I'm stuck with debugging but here's the code starting with javascript $('.test-parse').unbind().click(function() { parent = $(this).parent().parent(); var x = parent.find('.x').text(); var y = parent.find('.y').text(); var area_id = parent.find('.area').text(); if (area_id != '') { var area = areas[area_id]; } else { var area = null; } var cropped = $('.zoom-in').hasClass('btn-success'); if (cropped) { var img_url = $('#main-img-src').text(); } else { var img_url = $('.img-class').attr('src'); } var data = { 'x': x, 'y': y, 'image': img_url, 'width': $('.img-class').width(), 'height': $('.img-class').height(), 'color': parent.find('#color').css('background-color'), 'variance': parent.find('.color').val(), 'switch-color': parent.find('.switch-color').prop('checked'), 'new-color': parent.find('.color-code').val(), 'keep-perspective': parent.find('.perspective').prop('checked'), 'cls-id': parent.find('.cls-id').text(), 'area-id': area, 'grayscale': $('.gl-scale input').prop('checked'), } var unique_processing_id = ''; var task_id = ''; var csrftoken = $.cookie('csrftoken'); $.ajax({ url: "/start-render-part", type: "POST", dataType: 'json', beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) { // Send the token to same-origin, relative URLs only. // Send the token only if the method warrants CSRF protection // Using the CSRFToken value acquired earlier xhr.setRequestHeader("X-CSRFToken", csrftoken); … -
Why does docker-compose use ~60GB to build this image
When I start docker-compose build I have 60 gigs free. I run out of space before it finishes. Any idea what could possibly be going on? I'm running latest of Docker for Mac and docker-compose here's my docker-compose file: version: '3' services: db: image: postgres:9.6-alpine volumes: - data:/var/lib/postgresql/data ports: - 5432:5432 web: image: python:3.6-alpine command: ./waitforit.sh solr:8983 db:5432 -- bash -c "./init.sh" build: . env_file: ./.env volumes: - .:/sark - solrcores:/solr ports: - 8000:8000 links: - db - solr restart: always solr: image: solr:6-alpine ports: - 8983:8983 entrypoint: - docker-entrypoint.sh - solr-precreate - sark volumes: - solrcores:/opt/solr/server/solr/mycores volumes: data: solrcores: and my dockerfile for the "web" image: FROM python:3 # Some stuff that everyone has been copy-pasting # since the dawn of time. ENV PYTHONUNBUFFERED 1 # Install some necessary things. RUN apt-get update RUN apt-get install -y swig libssl-dev dpkg-dev netcat # Copy all our files into the image. RUN mkdir /sark WORKDIR /sark COPY . /sark/ # Install our requirements. RUN pip install -U pip RUN pip install -Ur requirements.txt This image itself when built is ~3 gigs. I'm pretty flummoxed. -
Django routing not working as expected
I know there should be a little thing that i missed. But I couldn't figure the problem out for ours. And I give up. Here is my root url conf: urlpatterns = [ url(r'^$', include('admin.urls')), ] And admin.urls file: urlpatterns = [ url(r'^$', views.index, name="index"), url(r'^user$', views.user, name='user'), ] When i hit "localhost/" index works great. But localhost/user (localhost/user/ too) is not working, i get 404 not found. admin is my application name so do not confuse it with django.contrib.admin. Django version :(1, 11, 5, 'final', 0) Python 3.6.2 -
docker nginx failed to make connection with web container
My docker nginx container failed to connect with gunicorn container. docker compose logs looks like, dj | [2017-09-16 12:37:14 +0000] [22] [INFO] Starting gunicorn 19.7.1 dj | [2017-09-16 12:37:14 +0000] [22] [DEBUG] Arbiter booted dj | [2017-09-16 12:37:14 +0000] [22] [INFO] Listening at: http://127.0.0.1:8000 (22) dj | [2017-09-16 12:37:14 +0000] [22] [INFO] Using worker: sync dj | [2017-09-16 12:37:14 +0000] [25] [INFO] Booting worker with pid: 25 dj | [2017-09-16 12:37:14 +0000] [22] [DEBUG] 1 workers ng | 2017/09/16 12:37:22 [error] 8#8: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 172.20.0.1, server: localhost, request: "GET /api HTTP/1.1", upstream: "http://127.0.0.1:8000/api/v1", host: "localhost" ng | 172.20.0.1 - - [16/Sep/2017:12:37:22 +0000] "GET /api HTTP/1.1" 502 537 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/52.0.2743.116 Chrome/52.0.2743.116 Safari/537.36" "-" ng | 2017/09/16 12:37:31 [error] 8#8: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 172.20.0.1, server: localhost, request: "GET /admin HTTP/1.1", upstream: "http://127.0.0.1:8000/api/admin", host: "localhost" ng | 172.20.0.1 - - [16/Sep/2017:12:37:31 +0000] "GET /admin HTTP/1.1" 502 537 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/52.0.2743.116 Chrome/52.0.2743.116 Safari/537.36" "-" If I make a curl request inside django container, it shows the relevant html text. $ … -
Unresolved library "staticfiles" - Pycharm Django
So, basically I can't access my static files because the {% load staticfiles %} tag gets highlighted with the "unresolved library" error message in my Pycharm project. I have django.contrib.staticfiles in my INSTALLED_APPS. My settings file: if DEBUG: MEDIA_URL = '/media/' STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static", "static-only") MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static", "media") STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static", "static"), ) -
Status Code 405 while using google oauth2
I am using Django with Angular JS to access the Google Drive API. I am following this document from Google. The FLOW.step1_get_authorize_url() gives me the URL similar to the sample URL mentioned on the page. But the problem is that after return HttpResponseRedirect(authorize_url) the browser does not redirect to the authorize_url and gives the error as shown in the picture below (Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8000' is therefore not allowed access. The response had HTTP status code 405). But if I copy pasted the URL, it works fine. The oauth2 function looks like this. def index(request): FLOW = flow_from_clientsecrets( settings.GOOGLE_OAUTH2_CLIENT_SECRETS_JSON, scope='https://www.googleapis.com/auth/drive', redirect_uri='http://127.0.0.1:8000/oauth2callback/' ) FLOW.params['access_type'] = 'offline' authorize_url = FLOW.step1_get_authorize_url() return HttpResponseRedirect(authorize_url) And here is the oauth2callback function. def auth_return(request): credential = FLOW.step2_exchange(request.GET) return HttpResponseRedirect("/mycustomurl") I used this to enable CORS in the Django Server Side. Here is my part of service in Angular that makes the call to oauth2. (function () { 'use strict'; angular.module('myApp') .service('myService', function ($http) { this.saveToDrive = function (startYear, endYear, shape) { var config = { params: { start: '1999', end: '2002', action: 'download-to-drive' }, headers: { 'Access-Control-Allow-Origin': '*', 'X-Requested-With': null … -
Unsupported SRS when saving polygon in SRID=0 field
I'm trying to save a polygon with the default GeoDjango admin widget in an SRID 0 field. It gives an SRSException. I don't get what's wrong here, must there be a SRID for polygons to be saved? If so, is there a work around as I wish to save the coordinates of the polygon in raw simple CRS given in Leaflet (image overlay giving one pixel as one unit iirc) and using the default SRID changes the coordinates. What I'm trying to do is just a fake map with markers and polygons on it. -
filter company based on category
I was doing the project on Django to get into it more deeply. I have a problem in the model part. There is a model Company, Product, Category. Company is simply the introduction part. Product model is about what product a company has and its divided into category which is ManyToManyField. I have list all the categories in a page where if certain category is clicked then the list of companies that has product of that category should be filtered. But I don't know how to access it. Here is my model class Category(models.Model): name = models.CharField(max_length=50) slug = models.SlugField(max_length=50, unique=True) class Product(models.Model): name = models.CharField(max_length=200, unique=True, blank=False, null=False) company = models.ForeignKey('Company', related_name='products', blank=True, null=True, on_delete=models.SET_NULL) website = models.URLField(unique=True) slug = models.SlugField(unique=True) categories = models.ManyToManyField(Category, related_name='products') class Company(models.Model): name = models.CharField(max_length=200, unique=True, blank=False, null=False) slug = models.SlugField(unique=True) description = models.CharField(max_length=400) editor = models.ForeignKey(User, related_name='company') # product = models.ForeignKey(Product, related_name='company') -
django redirect does not work
I wanted to have function that every time get the request and check that user is login and then return user object if user is login otherwise redirect to login , so this is what I tried to do def is_login(request): userID = request.session.get('mainSession', 0) next = resolve(request.path_info).url_name print(1) if userID != 0: print(2) user = msignup.objects.filter(id=userID).first() return user print(3) return HttpResponseRedirect(reverse('login') + "?next= {}".format(next)) I tried to test this function with below view when user is loged out and request has no mainSession : def email_activation(request): user = is_login(request) print(4) if req.method == 'GET': print(5) email = user.email return render(request, 'account/emailActivation.html',{'email': email}) return redirect('login') and in response I got this : 'HttpResponseRedirect' object has no attribute 'email' and the response for prints that I had made is : 1 3 4 5 why after 3 redirect does not happens ?what am I doing wrong? -
Permissions don't apply to users in extended group in Django
I have custom user model and extended group model. When I go to admin panel and set permissions in my extended group then it doesn't have any effect on users who are in that group. I checked database and everything looked correct. It works only when I put user to non-extended Group model even tho extended class should share permissions with parent one. settings.py AUTH_USER_MODEL = 'web.TurboM_User' models.py from django.contrib.auth.models import AbstractUser from django.contrib.auth.models import Group class TurboM_Group(Group): TurboM_Users = models.ManyToManyField('TurboM_User', blank=True, verbose_name="Users") is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) class Meta: verbose_name = "Group" verbose_name_plural = "Groups" class TurboM_User(AbstractUser): TurboM_Groups = models.ManyToManyField('TurboM_Group', through=TurboM_Group.TurboM_Users.through, blank=True, verbose_name="Groups") ADgroups = models.TextField(null=True, blank=True) domain = models.ForeignKey(Domain, null=True, blank=True) class Meta: verbose_name = "User" verbose_name_plural = "Users" admin.py class TurboM_GroupAdmin(admin.ModelAdmin): model = TurboM_Group fieldsets = [ (None, {'fields': ['name','is_staff', 'is_active',]}), (_('Permissions'), {'fields': ['TurboM_Users', 'permissions',]}), ] filter_horizontal = ('TurboM_Users', 'permissions',) admin.site.unregister(Group) admin.site.register(TurboM_Group,TurboM_GroupAdmin) -
Django template tags + using fabric.js
I've set up a reasonable Django site to test and play around with, but I'm having an awful time including fabric.js Ultimately I want to use fabric.js to take small images from a database and display them on a canvas, but I digress. The issue I'm having is that I cannot use a local png image within my html using fabric.js - I mean, fabric is included (because I can do very basic tricks with fabric, like create rectangles) However, the tutorial isn't clear on including local images. Here's my awful code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>This is using render</title> {% load staticfiles %} <script scr="{% static "js/fabric.js" %}" type="text/javascript"></script> </head> <body> <script type="text/javascript"> var canvas = new fabric.Canvas('c'); canvas.setHeight(480); canvas.setWidth(640); var imgElement = fabric.Image.fromURL('../static/images/pitch.png', function(oImg) { canvas.add(oImg); }); var imgInstance = new fabric.Image(imgElement, { left: 100, top: 100, angle: 90, opacity: 0.85 }); canvas.add(imgInstance); </script> </body> </html> Probably doing something noobish, so apologies in advance. -
Image Downsizing and Upsizing in React Native like Instagram
Instagram changes image pixels when user posts it. I think Instagram resizes image on the Front-End. When we uploads image, how can we downsize or upsize the image in React Native? For instance (I've done little a bit of research), 1. 192 x 263 image -> 320 x 400 fixed image (upsized by width 320) 2. 250 x 220 image -> 320 x 282 fixed image 3. 183 x 276 image -> 320 x 400 fixed image 4. 2048 x 1152 image -> 1080 x 608 fixed image (downsized by width 1080) 5. 683 x 1024 image -> 683 x 853 fixed image (downsized by width 683) if the width of the image is greater than 1080 or lower than 320, it resizes the image. About my app, I'm using Django REST framework for Backend and React Native for Front-End. I'm sending image using http gzip compression. If I'm not wrong, apps downsize or upsize image from Front-End and send it to Backend. I think this way is the most efficient. -
docker-compose django failed to connect to mysql instance
I'm having a hard-time to make django to communicate with mysql instance which runs on another container. I'm using docker-compose to set the services up. docker-compose.yaml version: '2' services: nginx: build: ./nginx container_name: ng01 ports: - "80:80" depends_on: - api api: build: ./api container_name: dg01 restart: always command: bash -c "python manage.py makemigrations && python manage.py migrate && gunicorn s2s_api.wsgi:application -b localhost:8000" depends_on: - db ports: - "8000:8000" tty: true links: - db:mysql db: image: mysql container_name: db01 command: mysqld --user=root --verbose ports: - "3306:3306" restart: always environment: MYSQL_DATABASE: "demo" MYSQL_USER: "root" MYSQL_PASSWORD: "avi" MYSQL_ROOT_PASSWORD: "avi" MYSQL_ALLOW_EMPTY_PASSWORD: "yes" DB_PORT: 3306 DB_HOST: db When i try to make the services up through docker-compose up command, it shows, it always shows like django.db.utils.OperationalError: (2003, "Can't connect to MySQL server on '127.0.0.1' (111)"). But running ping db, curl db:3306 inside api container works. It properly sends the ack message as well as the mysql version. I have also tried this https://stackoverflow.com/a/42703132/3297613 method. It prints starting daemon ... but failed to execute the next step. -
gunicorn for chat bot
I have a chat bot written in python django and deployed with gunicorn. I started 12 workers on cpu with 2 cores. More than 12 I do not run, because the documentation is not recommended, but my cpu is loaded 7 percent maximum. Why I can not run 20 processes and more? Maybe I need run worker with multiple threads? I tried, but bot send many responce on one request. How can I start using all the resource of the processor? Maybe it's worth deploying the application to a different technology instead of gunicorn? Gunicorn i'm running so: nohup gunicorn --workers=12 --max-requests=5000 --bind 127.0.0.1:8000 exgirlbot.wsgi:application & Maybe i just need to set confugiratio? Thank you. -
Architectural design of an SQL & Document Database based Web Application
I am designing a web application with Django as the backend. Overview of the system is as follows Data is collected from user related to different entities. Example : Plant, Project, Machine, Test, etc. Configuration Blocks (consolidated, fully self contained, dated & versioned JSON files) are created by user by selecting different instances of above entities into a package. The config block is sent to an automated API server, which generates an API for the said block on the fly. I am trying to model the database structure the step 1. Known details Different classes of entities. Ex. Plant, Project, Machine, etc are known before hand and are fixed. Everything else is unknown. I don't know the data in the entities, the links between them, etc. I plan to user Postgres for a searchable relational data and a document database, CouchDB to handle the unknown data schema part. Envisaged Architecture I plan to have template tables for different entities, in a Postgres database, where, the administrator defines a set of templates for data required to be filled by the user. The template is a JSON document, with a protocol for defining different fields the user will fill out. My UI … -
Using For-Variables for Django Model coloumn
Dunno if its possible. Hopefully u guys knows what I try to do. I wanna do the model changes in a FOR loop cause the keys of the values have always the same name as the model coloums. My currently code: sites = DataModel.objects.all() for site in sites: d = self.getDataBySoup(soup) site.title = d['title'] site.text = d['text'] site.facebook = d['facebook'] site.twitter = d['twitter'] site.save() As you can see, the keys are always the same as the django coloumns. So I thought its maybe possible to do it with less code. What I tried (But not working): sites = DataModel.objects.all() for site in sites: d = self.getDataBySoup(soup) for key, value in d.items(): site.key = value site.save() I use Python 3.6