Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django, get canvas data and using it in views.py
I'm new to web development. I research this question online but can not find a proper solution yet. I want to create a web site that allows the user to draw a number on a canvas and the website can predict the number after clicking the button. My idea is to get the canvas data by using getImageData and put the data into the views.py. Right now I can saw my ImageData in the console, but I don't know how to load the data to views.py where I will run python code for the classification. function hwdClick() { document.getElementById("hwdB").innerHTML = "YOU CLICKED ME!"; var canvas = document.getElementById("hwdcanvas"); var ctx = canvas.getContext("2d"); var canvasData = ctx.getImageData(0,0,350,350); console.log(canvasData); } Do I have to use database in this case? Please give me some hint on this problem. -
"Base classes have conflicting values for attribute" when using a Python mixin to overide a base class method
I have a django mixin: class PublicSchemaOnlyAdminAccessMixin: def has_view_or_change_permission(self, request, obj=None): return connection.schema_name == get_public_schema_name() def has_add_permission(self, request): return connection.schema_name == get_public_schema_name() def has_module_permission(self, request): return connection.schema_name == get_public_schema_name() That is used in many of my ModelAdmin classes, for example: class BlockAdmin(PublicSchemaOnlyAdminAccessMixin, admin.ModelAdmin): pass But I'm getting warning about this structure from LGTM: Base classes have conflicting values for attribute 'has_add_permission': Function has_add_permission and Function has_add_permission. However, none of their proposed solutions seem to be practical for this, since I am using this in about half of my Admin classes. Is there either A. A better way for me to resolve this bad code structure or B. Is this code structure fine (as long as I understand the classes are read from right to left and the mixin must go on the left for consistant behaviour) -
How to save a HTML Canvas content to Google Storage
I am trying to save an html canvas content to Google Storage. What I do is as following : Create a signed url for the image file. class ThumbnailUploadSignedURL(APIView): @method_decorator(login_required(login_url='/login/')) def post(self, request): filename = request.POST.get('filename') filetype = request.POST.get('type') filesize = request.POST.get('size', 0) path = '{0}-{1}/{2}/'.format(request.user, request.user.id, thumbnail.name) blob = default_storage.open(full_path, 'wb') signed_url = blob.blob.generate_signed_url(expiration=default_storage.expiration, method='PUT', content_type='image/png') return Response({"thumbnail_signed_url":signed_url}) Get the content of canvas and send it to Google Storage. var image = canvas.toDataURL("image/png"); const xhr = new XMLHttpRequest(); xhr.open("PUT", data.thumbnail_signed_url, true); xhr.setRequestHeader('Content-Type', 'image/png'); xhr.send(image); The file is successfully being created on Google Storage, however the content is stated as corrupt, it is indeed basically base64. I also tried ways to convert base64 to png, yet unsuccesfully, as it was suggested here php-js-canvas example. How can I achieve this with js and google storage ? -
Django - recycle form field variable twice
I have a page where the user can create a new team, the html page is divided as such: user inputs a team name (if they want to, the page can return an animation with JS) First form by clicking next, it brings to the 2nd part: where the user inputs the team key others can use to join the team Second form Once the user clicks submits, it needs to be submitted as one form (team name + team key) to process. My problem is that I wish to reuse the {{form.team_name}} value for the 2nd part that I will use for a team creation. The form.py values look like this: class TeamCreationForm(forms.Form): team_name= forms.CharField(max_length=100, widget= forms.TextInput (attrs={ 'placeholder': 'MY TEAM', 'id':'inputText'})) team_k = forms.CharField(max_length=100, widget= forms.TextInput (attrs={ 'placeholder': 'ENTER KEY', 'id':'inputText'})) my team creation page looks like this: [...] <button style="float:left;">Go Back</button> <div> <canvas id="text" width="500" height="100"></canvas> <canvas id="stage" width="500" height="100"></canvas> </div> <div> <div id="Div1"> <form id="form"> {{form.team_name}} <input type="submit" value="TRY IT"> </input> <button type="button" id="nextBtn" onclick="switchVisible();">Next</button> </form> </div> <div id="Div2"> <form id="form" method="POST" style="top:342px; left:340px;">{% csrf_token %} {{form.team_k}} <input type="submit" value="CREATE"> </input> <button type="button" id="nextBtn" onclick="switchVisible();">Previous</button> </form> </div> </div> [...] For it to work, I would need … -
Heroku app crashes after pushing change with new dependencies
So I have a Django web app running on Heroku. I recently pushed an update where I added some API functionality via the Django Rest Framework. I installed this via pip. Now my Heroku app crashes. I assume I somehow need to install this dependency on Heroku? Here is the error message: An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command heroku logs --tail I tried entering the Heroku CLI and typing pip install djangorestframework but and running Heroku restart but it still crashes. -
Integrate twilio into webapp using postgres
I have a django app which stores phone numbers into a postgres database, I am looking to send sms to each of the numbers in the database as they are added via the webapp. I'm using pgadmin to monitor the database and it's all running on my localhost as of now, do I need to deploy it to get twilio working with the database? I can't seem to find any clear explanation as to how I can send the messages to the numbers stored as records in postgres, any help would be awesome! -
Issue with accessing Django Admin with the User table on the remote database and Django Native Admin related tables on the local databases
I'm trying to access the Django Admin using two databases. One is a local, while the other remote readonly legacy database has the User table. After logging in I get an error because the django_admin_log table is on the local database can't access the user table on the remote database. I'm using Django version 3.0.5. How could I fix this issue? -
django orderered model package
I use django ordered model to order my lines. when i drag and drop the file order from the front end. I call and endpoint to move the file to the next position. but in the response the order doesn't change. here is code models.py class Line(OrderedModel): """ Represents a segmented line from a document """ # box = gis_models.PolygonField() # in case we use PostGIS content = models.CharField(max_length=200,null=True,blank=True) document = models.ForeignKey(Document, on_delete=models.CASCADE, related_name='lines') # text direction order_with_respect_to = 'document' version_ignore_fields = ('document', 'order') external_id = models.CharField(max_length=128, blank=True, null=True) class Meta(OrderedModel.Meta): pass serializers.py class LineMoveSerializer(serializers.ModelSerializer): index = serializers.IntegerField() class Meta: model = Line fields = ('index',) def __init__(self, *args, line=None, **kwargs): self.line = line super().__init__(*args, **kwargs) def move(self): self.line.to(self.validated_data['index']) views.py @action(detail=True, methods=['post']) def move(self, request, document_pk=None, pk=None): line = get_object_or_404(Line, pk=pk) serializer = LineMoveSerializer(line=line, data=request.data) if serializer.is_valid(): serializer.move() lines = Line.objects.filter(document_part=part_pk).values('pk','order') return Response(status=status.HTTP_200_OK,data= {'moved': lines}) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
How to change the default image location in the Django ImageField?
Having trouble trying to change where Django looks for the default image in the ImageField. I am trying to store a default image within a folder in my "media" file. Code from models.py below: from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='profile_pics/default.jpg', upload_to='profile_pics') When I load the page I get a 404 error: Not Found: /media/default.jpg [21/Apr/2020 18:11:48] "GET /media/default.jpg HTTP/1.1" 404 1795 Any ideas on how to add the "profile_pics" piece to the path? -
How to serve static files using Traefik and Nginx in docker-compose
I am trying to serve static files using Traefik and Nginx, also docker. My Django application works well, I can access all pages, but can't setup static files serving. Here is my docker configuration. For the code skeleton, I am using cookiecutter-django django: build: context: . dockerfile: ./compose/production/django/Dockerfile image: dreamway_team_production_django depends_on: - postgres - redis env_file: - ./.envs/.production/.django - ./.envs/.production/.postgres command: /start postgres: ** traefik: build: context: . dockerfile: ./compose/production/traefik/Dockerfile image: dreamway_team_production_traefik depends_on: - django - nginx volumes: - production_traefik:/etc/traefik/acme ports: - "0.0.0.0:80:80" - "0.0.0.0:443:443" redis: ** nginx: image: nginx:1.17.4 depends_on: - django volumes: - ./config/nginx.conf:/etc/nginx/conf.d/default.conf - ./dreamway_team/static:/static and my config for traefik log: level: INFO entryPoints: web: address: ":80" web-secure: address: ":443" certificatesResolvers: letsencrypt: acme: email: "mail" storage: /etc/traefik/acme/acme.json httpChallenge: entryPoint: web http: routers: web-router: rule: "Host(`[DOMAIN_NAME]`)" entryPoints: - web middlewares: - redirect - csrf service: django web-secure-router: rule: "Host(`[DOMAIN_NAME]`)" entryPoints: - web-secure middlewares: - csrf service: django tls: certResolver: letsencrypt middlewares: redirect: redirectScheme: scheme: https permanent: true csrf: headers: hostsProxyHeaders: ["X-CSRFToken"] services: django: loadBalancer: servers: - url: http://django:5000 providers: file: filename: /etc/traefik/traefik.yml watch: true Any help would be appreciated! Thanks! -
Cannot install whitenoise
I am attempting to run the command pip install django-heroku, but whenever I do, it stops with the error ERROR: Package 'whitenoise' requires a different Python: 2.7.16 not in '>=3.5, <4'. I have tried to run pip install whitenoise, but that doesn't work. Same error. I am using Python 3.8.2 -
Django model form, not saving to DB correctly
I've looked at a couple of other questions on here, but can't seem to get any results.. I don't seem to get any errors thrown at me, so I'm not sure where I'm going wrong. I believe I may be using the primary key incorrectly. I do not want to put 'User' under my model form as it would allow someone to change someone else's fields. class history(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) gallons_requested = models.IntegerField() delivery_address = models.CharField(max_length=100) delivery_date = models.DateField() suggested_price = models.DecimalField(max_digits=6, decimal_places=2) total_amount_due = models.DecimalField(max_digits=6, decimal_places=2) def testing(request): if request.method == 'POST': form = RequestForm(request.POST, instance=request.user) if form.is_valid(): form.save() return redirect('pricing_module') else: form = RequestForm(instance=request.user) args = {'form': form} return render(request, 'pricing_module.html', args) -
how can i get all the data from my model booking having date less than today i want to show the booking history of customer
view.py def Profile(request,uid): book =booking.objects.filter(user=uid) user =User.objects.get(id=uid) books = booking.objects.filter(created__lt=datetime.today(),user=uid) params={'book':book,'user':user,'books':books} return render(request, 'hotel/userProfile.html',params) -
windows django data source name not found and no default driver specified
I'm trying to connect to SQL Server studio v17.2 This is the code that works fine in my local computer DATABASES = { 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 'ENGINE': 'sql_server.pyodbc', 'NAME': 'database', 'HOST': '10...', 'USER': 'user', 'PASSWORD': 'password', #'DRIVER':'ODBC Driver 17 for SQL Server' 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server',} } } This is the error I am getting: windows django data source name not found and no default driver specified -
How to test if the billing address provided is linked to the card number Stripe
I am trying to implement stripe in my website. I am using the test mode of stripe and using their provided card numbers for testing purpose. But I also want to check if any random billing address is linked to the card. I want to create a test scenario in which a card number is linked to a billing address and later in my website I want to enter random data billing to address if the payment fails or not. Is there anything in stripe that would help me achieve this functionality. -
Django, how can open modal form with value using jquery?
I'm new at django and jquery, I have a data table in which in the last column I have created the bottom "edit" that give me the possibility to modify the value of the row data. But when I clcik on the bottom and open the html modal, all fields are empty, but I want that it give me the value of single items as stored. My Modal: <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button> <h4 class="modal-title" id="myModalLabel">Modifica Materia Prima</h4> </div> <form id="updateUser" action=""> <div class="modal-body"> <input class="form-control" id="form-id" type="hidden" name="formId"/> <label for="codice">codice</label> <input class="form-control" id="form-codice" type="text" name="formCodice"/> <label for="tipologia">tipologia</label> <input class="form-control" id="form-tipologia" type="text" name="formTipologia"/> <label for="sottocategoria">sottocategoria</label> <input class="form-control" id="form-sottocategoria" type="text" name="formSottocategoria" min=10 max=100/> </div> <div class="modal-footer"> <button type="submit" class="btn btn-primary" >Save changes</button> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </form> </div> </div> My Javascript $("form#updateUser").submit(function() { var idInput = $('input[name="formId"]').val().trim(); var codiceInput = $('input[name="formCodice"]').val().trim(); var tipologiaInput = $('input[name="formTipologia"]').val().trim(); var sottocategoriaInput = $('input[name="formSottocategoria"]').val().trim(); if (codiceInput && tipologiaInput && sottocategoriaInput) { // Create Ajax Call $.ajax({ url: '{% url "crud_ajax_update" %}', data: { 'id': idInput, 'codice': codiceInput, 'tipologia': tipologiaInput, 'sottocategoria': sottocategoriaInput }, dataType: 'json', success: function (data) { if … -
module 'django.contrib.messages.constants' has no attribute 'success'
The documentation of django says 'success' is a function of django.contrib.messages.constants but when I execute django.contrib.messages.constants.success ,error comes as module 'django.contrib.messages.constants' has no attribute 'success' Error AttributeError at /contact module 'django.contrib.messages.constants' has no attribute 'success' Request Method: POST Request URL: http://127.0.0.1:8000/contact Django Version: 3.0.5 Exception Type: AttributeError Exception Value: module 'django.contrib.messages.constants' has no attribute 'success' Exception Location: C:\Users\User\PycharmProjects\Django\Hello\home\views.py in contact, line 35 Python Executable: C:\Users\User\AppData\Local\Programs\Python\Python38\python.exe Python Version: 3.8.0 Python Path: ['C:\Users\User\PycharmProjects\Django\Hello', 'C:\Users\User\AppData\Local\Programs\Python\Python38\python38.zip', 'C:\Users\User\AppData\Local\Programs\Python\Python38\DLLs', 'C:\Users\User\AppData\Local\Programs\Python\Python38\lib', 'C:\Users\User\AppData\Local\Programs\Python\Python38', 'C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages', 'C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages\pyzmail-1.0.3-py3.8.egg', 'C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages\distribute-0.7.3-py3.8.egg', 'C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages\win32', 'C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages\win32\lib', 'C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages\Pythonwin'] views.py from django.shortcuts import render, HttpResponse from datetime import datetime from home.models import Contact from django.contrib.messages import constants as messages def contact(request): if request.method == 'POST': name = request.POST.get('name') email = request.POST.get('email') phn = request.POST.get('phn') desc = request.POST.get('desc') cont = Contact(name=name,email=email,phn=phn,desc= desc,date=datetime.today()) cont.save() messages.success(request, 'Your mesaage has been sent') return render(request, 'contact.html') models.py from django.db import models class Contact(models.Model): name = models.CharField(max_length=122) email = models.CharField(max_length=122) phn = models.CharField(max_length=13) desc = models.TextField() date = models.DateField() admin.py from django.contrib import admin from home.models import Contact # Register your models here. admin.site.register(Contact) settings.py """ Django settings for Hello project. Generated by 'django-admin startproject' using Django 3.0.5. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their … -
Django html extends tags
This is my base.html <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> </head> <body> {% block content %}{% endblock content %} </body> </html> This is home_page where I am using the {% extends 'base.html' %} {% load static %} {% block content %} <div class="container"> <h1>{{ title }}</h1> <h1>Hello, world!</h1> <img src="{% static 'img/myImage.jpg' %}" class='img-fluid'> </div> {% if premium_content %} <div class="row"> <div class="col"> <h1>Premium</h1> {{ premium_content }} </div> {% endif %} </div> {% endblock content %} The here is my views.py where I have the home_page and before using the extends tag I could render this page properly def home_page(request): context = { "title":"Hello World We Working" } if request.user.is_authenticated: context["premium_content"] = 'Only premium users see this' return render(request, 'MainApp/home_page.html', context) The error message that I am getting is TemplateDoesNotExist at / Which I do not understand I even tried putting the two html files in the same directory but still I get the same error message -
Django Vote System - django-secretballot and django-vote both are falty for me, should I write voting system myself?
I would like to ask you for your help. I want to have some simple voting system on my django app. I googled it and I found two systems and some posts about not reinventing wheel and I am all for that :P First I tried to go with django-vote, it was updated two years ago. I setup it, added into apps, models, created function for it with user_id but I got error with "LazyObject". user_id from django-vote was expecting int, and not actual user name like it is in my app. So I went with django-secretballot next. But soon after adding it into middleware and apps I am getting error while I want to migrate: ImportError: cannot import name 'python_2_unicode_compatible' from 'django.utils.encoding' And right now I am lost. Should I try to ask for help and try to fix any of those two applications or I should look for another one or try to write it myself since I need only basic functions? Which approach would be better? Thanks and Cheers! -
DJANGO_SETTINGS_MODULE
Regarding : django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I have tried every possible solution that is out there on the web, but unfortunately without any luck so far. I have noticed however that Django is not appearing under 'File -> Settings -> Languages & Frameworks', although it seems I have installed it properly (I am able to retrieve Django version number 3.0.5 and when I run manage.py, I get a list of the available subcommands). Also 'os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Eric.settings')' is properly set in manage.py file. Still I am running into the above error whenever I try to run 'django-admin runserver' ! I was expecting to find Django in the Languages & Frameworks section, but it seems to be missing there. Is this OK or NOK ? Thanks -
IntegrityError (1452, 'Cannot add or update a child row: a foreign key constraint fails)
I'm using a custom user model (following this tutorial) and all works well. When I'm logged in with the admin user I created with createsuperuser in the /admin session I can add/remove/edit anything I want. When I'm logged in with some other user, to which I've given staff and admin powers, I get this error whenever I want to add something to the database: IntegrityError at /admin/users/user/13/change/ (or whichever action I'm doing) (1452, 'Cannot add or update a child row: a foreign key constraint fails (`NMS_database`.`django_admin_log`, CONSTRAINT `django_admin_log_user_id_c564eba6_fk_auth_user_id` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`))') [...]Exception Location: /home/me/python_ve/lib/python3.8/site-packages/MySQLdb/connections.py in query, line 239 This is my user model: class User(AbstractBaseUser): email = models.EmailField(verbose_name="email", unique=True, max_length=255) first_name = models.CharField(max_length=30, blank=True, null=True) surname = models.CharField(max_length=30, blank=True, null=True) additional = models.BooleanField(default=False) individual = models.BooleanField(default=True) active = models.BooleanField(default=True) #can they login? staff = models.BooleanField(default=False) #staff user non superuser admin = models.BooleanField(default=False) #superuser date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' # default identifier for that user which will used for logging in #email (USERNAME_FIELD in this case) and password are required by default REQUIRED_FIELDS = ['first_name', 'surname'] def __str__(self): return "%s %s" % (self.first_name, self.surname) def get_full_name(self): return self.first_name def has_perm(self, perm, obj=None): return self.admin def has_module_perms(self, app_label): … -
Django - printing variables in templates
I created an app called "jobs", basically I'd like to create new "jobs" from the admin console and be able to post it on the jobs.html page. I created the model and views but I think there is something wrong with the views that doesn't allow me to print the "jobs" on the html template. Can you please me if the error is in views.py? jobs/models.py from django.db import models # Create your models here. class post_job(models.Model): posizione= models.TextField(max_length=20) descrizione= models.TextField(max_length=20) requisiti= models.TextField(max_length=20) def __str__(self): """String for representing the MyModelName object (in Admin site etc.).""" return self.posizione jobs/admin.py from django.contrib import admin from .models import post_job # Register your models here. admin.site.register(post_job) jobs/views.py from django.shortcuts import render from .models import post_job # Create your views here. def viz_job(request): posizione = post_job.posizione print(posizione) return render(request,'jobs/jobs.html',{'posizione':posizione}) -
JSON value doesn't change inside ajax success callback function
I'm working on a django reddit clone project, just to improve my skills. I wanted to implement AJAX to it so the page doesn't refresh when someone upvotes. I made an API with django rest framework, which has upvoted and downvoted boolean values. However, when I try to change the upvoted value to false in my javascript, it doesn't work, but changing it to true when it's false works and updates the template. This is probably confusing so here is some code. class UpvoteAPIToggle(APIView): def get(self, request, id=None, format=None): post = Post.objects.get(id=id) all_post_upvotes = post.upvotes.all() all_post_downvotes = post.downvotes.all() profile = Profile.objects.get(user=self.request.user) upvoted = False downvoted = False if profile not in all_post_upvotes: post.upvotes.add(profile) downvoted = False if profile in all_post_downvotes: post.upvotes.remove(profile) upvoted = False downvoted = True else: post.downvotes.remove(profile) upvoted = True serializer = PostSerializer(all_post_upvotes, many=True, read_only=True) serialized_upvotes = serializers.serialize("json", all_post_upvotes) upvote_counter = 0 data = { "upvoted":upvoted, "downvoted": downvoted, "all_post_upvotes":serialized_upvotes, "upvote_counter":upvote_counter } return Response(data) this is the class based rest view. $.ajax({ url: upvoteUrl, data: {}, dataType: "json", success: (data)=>{ checkVote(data) } }) function checkVote(data){ if (data.upvoted){ data.upvote_counter--; data.upvoted = false }else{ data.upvote_counter++; data.upvoted = true $(".upvote-btn").css("color","orange"); $("#upvoteCounter").text(data.upvote_counter) } } Here is the jquery part from the template. It … -
Dealing with byte literals in Django unit tests
I have this line in my unit test: self.assertEqual(get_response.content, f'APIUserMiddleware User, {remote_user}, does not exists.') This fails with this output: AssertionError: "b'APIUserMiddleware: User, bad.gen, does not exists.'" != 'APIUserMiddleware User, bad.gen, does not exists.' How should I deal with the byte literal being returned from an API? -
Scrapy pipelines Django update item in database SQLite
In my Scrapy project connected with Django, I scrape pages with offerts for housing markets and save in database. In pipelines file I create unique hash_id for each item and with other data save in db. Each time I want to update db for new offerts (it works) but also for closed offerts (not displayed more on page) change status in db for 'not active'. How to do that when process_item works only for specific scrapped item? My idea was to collect all hash_id from db in list, check scrapped items if their hash_id are in. If yes, delete the hash_id from list. Then update remaining items status. But it doesn't work. My pipelines file: def hashed_list(): hashed_items_db = Offert.objects.filter(still_active = True) hashed_list=[item.hash_id for item in hashed_items_db] return hashed_list class ScraperPipeline(object): hashed_list = hashed_list() def create_hash(self, *args): ... return data def process_item(self, item, spider): ..... hash_id = self.create_hash(args) item['hash_id'] = hash_id if hash_id not in hashed_list: item.save() else: hashed_list.remove(hash_id) return item def close_spider(self, spider): for hash_item in hashed_list: obj =Offert.objects.get(hash_id=hash_item) obj.still_active = False obj.end_date = timezone.now() - timedelta(days=1) obj.save() return hashed_list How to do that? Is there any easy (??) way to update non scrapped items in db?