Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - PWA // How do I need to setup user data management?
I'm working on a pwa with django and I almost done all the front/backend and I'm now facing which might be the last part to put in place (I believe and hope so !) : User Data Management I already had a look at Django's documentation regarding user/group management and I think it is quite logical and understandable however I'm really stuck on how should I implement all of this according to my project ? And especially how should I manage user's data ? Today, the development part is already setup with models/data saving/editing. But there's no user dimension for now, everything created and stored in the database is "general" (I'm using SQLite3 mainly because it was easier to deal with for development and testing but I'm clearly not fixed to it and I can easily readapt parts of the code based on the chosen database and how it work, even more if other database are better adapted to what I am looking for). To give you a bit of context the application should allow anyone to create an account to access the app. When he user is logged on, he/she will be able to arrive on an interface with … -
Django loses static files
When I make changes in my static files it doesn't load in my website and I have to change the name of my static file to load it how can I solve this problem? my settings.py: STATIC_URL = '/static/' MEDIA_URL = '/images/products/' STATICFILES_DIRS = [ BASE_DIR / "static", '/var/www/static/', ] MEDIA_ROOT = BASE_DIR / "static/images/products/" HTML : {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static '/css/style.css' %}"> <script type="text/javascript"> var user = "{{request.user}}" </script> <title>Ecom</title> </head> <body> {% include 'store/nav.html' %} <div class="container"> {% block content %} {% endblock content %} </div> </body> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> <script type ='text/javascript' src="{% static "js/cart.js" %}"> </script> </html> -
No module named 'search.api'
I am trying to import code using this command: python manage.py makemigrations and i am getting this error while importing how can I find the search.api error, is this a package of python or django? if these are one of the libraries then help me out to find the search api. I have also tried the google search api but it contradicts the version of my selenium. whenever I upgrade the version of my selenium these google api wont work. File "/home/ali/Desktop/Darkbot/Project/adminpanel/views.py", line 26, in <module> from search.api.views import saveMonitorEmail, saveCurrentStatus, darkbotEmailReport, darkbotDomainReport ModuleNotFoundError: No module named 'search.api' (env) ali@kali:~/Desktop/Darkbot/Project$ -
I am trying to get users' actual ip addresses using nginx
Project set up with Docker and front-end built with Quasar, back-end built with Django Rest Framework Frontend nginx.conf: include /etc/nginx/mime.types; upstream gobazar { server backend:8000; } server { listen 8080; root /usr/share/nginx/html; index index.html index.htm; # frontend location / { try_files $uri $uri/ /index.html; } location @rewrites { rewrite ^(.+)$ /index.html last; } location ~ ^/(admin|api) { proxy_pass http://gobazar; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } # django static files location /static/ { autoindex on; alias /usr/src/app/static; # alias /home/app/web/static/; } error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; } } Please help me out if it is possible to get user's real ip address! -
How to display the submitted client data on django
I want to create a client server application with Django. Client on linux transfers data to server (django). The client uses curl to send data to django. How can I display all this in django? I want to run this statement: whith curl awk '{u=$2+$4; t=$2+$4+$5; if (NR==1){u1=u; t1=t;} else print ($2+$4-u1) * 100 / (t-t1) "%"; }' \ <(grep 'cpu ' /proc/stat) <(sleep 1;grep 'cpu ' /proc/stat) I make a model in models.py from django.db import models class Articles(models.Model): title = models.CharField('CPU Utilization %', max_length=100) def __str__(self): return f'CPU Utilization:{self.title}' class Meta: verbose_name = 'CPU Utilization' verbose_name_plural = 'CPU Utilization' views.py from django.shortcuts import render from .models import Articles def index(request): axbor = Articles.objects.all() return render(request, 'cpu/index.html', {'axbor':axbor}) urls.py from django.urls import path, include from . import views urlpatterns = [ path('', views.index), ] index.html {% extends 'cpu/layout.html' %} {% block title %} Index page {% endblock %} {% block content %} <div class="alert alert-info"> <h3>Monitoring CPU usage </h3> </div> {% if axbor %} {% for el in axbor %} <div class="alert alert-warning"> <h3>{{ el.title }}</h3> </div> {% endfor %} {% else %} <div class="alert alert-warning"> <h3>You have no entries!</h3> </div> {% endif %} {% endblock %} -
Django Channels - Custom Authentication Middleware raises: 'coroutine' object is not callable
I have created a custom token authentication middleware. from rest_framework.authtoken.models import Token from django.contrib.auth.models import AnonymousUser from django.db import close_old_connections from asgiref.sync import sync_to_async class TokenAuthMiddleware: """ Token authorization middleware for Django Channels 2 """ def __init__(self, inner): self.inner = inner def __call__(self, scope): # Close old database connections to prevent usage of timed out connections sync_to_async(close_old_connections)() headers = dict(scope['headers']) try: token_name, token_key = headers[b'sec-websocket-protocol'].decode().split(', ') if token_name == 'Token': token = sync_to_async(Token.objects.get, thread_sensitive=True)(key=token_name) scope['user'] = token.user else: scope['user'] = AnonymousUser() except Token.DoesNotExist: scope['user'] = AnonymousUser() return self.inner(scope) When I run it, an exception happens when I run scope['user'] = token.user [Failure instance: Traceback: <class 'AttributeError'>: 'coroutine' object has no attribute 'user' I tried awaiting the Token query like this: token = await sync_to_async(Token.objects.get, thread_sensitive=True)(key=token_name) and I added async in front of the __call__ function, but then the following error is raised before any of the code inside the __call__ function runs: [Failure instance: Traceback: <class 'TypeError'>: 'coroutine' object is not callable I am using Django v3.0.6 and Django Channels v2.4.0 -
Can we bring go and python together?
I wanted to understand whether we can bring in the efficiency and speed of Golang in data and calculation intensive tasks and couple it with django or python to serve the results? wherein python-django would be the mothership with small containers of Go-lang, specialized for specific tasks.? How do we go about it? sorry if the question may seem lame for my lack of knowledge. Thanks in advance. -
how to deploy django with react web app on heroku?
I am try to Deploy app but heroku shows APPLICATIONS error but build package upload was successful, I am visit error log gunicon package error web: gunicorn backend.wsgi --log-file -``` -
Django: Accounts activated automatically when sending verification emails
I have a problem in activating accounts on Django. When I send a clickable verification link by email, the account is getting activated automatically without needing the users to click on the link (I saw that the account was indeed activated without needing to click on it). On the other hand, when I send a non clickable link (so by removing the http:// in the beginning), the client can copy the link and paste and verify his account normally. I need to send a clickable link that require a user to manually click on it so his account gets activated. In views.py Registation function mail_subject = 'Activate your blog account.' message = render_to_string('main/acc_active_email.html', { 'user': user, 'domain': example.com, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) to_email = form2.cleaned_data.get('email') email = EmailMessage( mail_subject, message, to=[to_email, ] ) email.send() Activation function def activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() login(request, user) data = 1 context = {'data': data} return render(request=request, template_name="main/accept_email.html", context=context) else: return HttpResponse('Activation link is invalid!') In confirmation email: {% autoescape off %} Hi {{ user.username }}, Please click on … -
ValueError at /blog/addblog
I am trying to implement the add post section in my website where the user can add his blog. the page looks like this: but when I am trying to post by clicking the post button I get this error: ValueError at /blog/addblog Field 'sno' expected a number but got 'blog title'. Request Method: POST Request URL: http://127.0.0.1:8000/blog/addblog Django Version: 3.1 Exception Type: ValueError Exception Value: Field 'sno' expected a number but got 'blog title'. Exception Location: C:\Users\jayant nigam\projects\practise\lib\site-packages\django\db\models\fields\__init__.py, line 1776, in get_prep_value Python Executable: C:\Users\jayant nigam\projects\practise\Scripts\python.exe Python Version: 3.8.5 Python Path: ['C:\\Users\\jayant nigam\\projects\\everythingcs', 'C:\\Python38\\python38.zip', 'C:\\Python38\\DLLs', 'C:\\Python38\\lib', 'C:\\Python38', 'C:\\Users\\jayant nigam\\projects\\practise', 'C:\\Users\\jayant nigam\\projects\\practise\\lib\\site-packages'] Server time: Sat, 24 Oct 2020 15:17:48 +0530 blog models.py: class Post(models.Model): sno = models.AutoField(primary_key=True) title = models.CharField(max_length=50) content = RichTextField(blank=True, null=True) # content = models.TextField() author = models.CharField(max_length=50) slug = models.SlugField(max_length=200) timeStamp = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-timeStamp'] def __str__(self): return self.title + " by " + self.author views.py def addblog(request): if request.method == 'POST': title = request.POST.get('title') content = request.POST.get('content') author = request.POST.get('author') slug = request.POST.get('slug') blog = Post(title, content, author, slug) blog.save() return render(request, 'blog/add_post.html') add_post.html {% extends 'base.html' %} {% block title %} add post {% endblock title %} {% block body %} … -
override admin.site make admin.py another app doesn't show at django admin
On my project, there are multiple app, so i also have admin.py each folder. Here are some of my admin.py api/admin.py from django.contrib import admin from .models import Message @admin.register(Message) class MessageAdmin(admin.ModelAdmin): list_display = ['source','name','created'] list_filter = ['source','created'] search_fields = ['message'] dummy/admin.py from django.contrib.admin import AdminSite from dummy.forms import MyAdminLoginForm # export admin.py another app from api.models import Message from api.admin import MessageAdmin class MyAdminSite(AdminSite): login_form = MyAdminLoginForm login_template = 'dummy/templates/admin/login.html' site = MyAdminSite() site.register(Message,MessageAdmin) Since i wanna use captcha on django admin login, i should override the login form that inherit from AdminSite via dummy/admin.py. After that i registering the custom login on the main url from django.contrib import admin from django.urls import path, include from dummy.admin import site admin.site = site urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('api.urls')) ] You can see that i re registering the api/admin.py on the dummy/admin.py, i did it because if i didn't re registering the api/admin.py, it won't be show at the django admin. what should i do to make the admin.py another app doesn't need to be re register like it used to be when i use custom login form that inherit from AdminSite -
Best way to save data serialized by Django Restful frameork to django storage?
I have a requirement to save some data serialized from django restful framework. My view is on a url like /api/fruits/status=ripe I can save the data using the test client, is that the best way, or are there other better ways to do the same thing ? -
Why in django admin foreign key displays attribute value but in angular and database it returns id?
In Django admin, foreign key displays attribute value but in angular it returns id. DepartmentID is a foreign key which is displayed as dpt_name in dajngo admin but in database and anguar it is stored as id. How to Display Foreign Key Value instead of ID in Angular 9? models.py Department table class Department(models.Model): DepartmentID = models.CharField(max_length=20, primary_key = True, verbose_name='Department ID') dpt_code = models.CharField(max_length=20, verbose_name='code', unique = True, blank = False, null = False) dpt_name = models.CharField(max_length=50, verbose_name='name', unique = True, blank = False, null = False) class Meta: db_table = '"tbl_department"' verbose_name_plural = "Department" def __str__(self): return self.dpt_name Program Table class Program(models.Model): programCode = models.CharField(max_length=3, primary_key = True, verbose_name='Program Code', unique = True) pro_name = models.CharField(default = 'B.Sc. Engg. in CSE', max_length=50, verbose_name='name', blank = False, null = False) pro_shortForm = models.CharField(default = 'CSE',max_length=20, verbose_name='short Form', blank = False, null = False) DepartmentID = models.ForeignKey('Department', on_delete=models.CASCADE, verbose_name='department', db_column="DepartmentID") TYPE_CHOICES = ( ('honours', 'honours'), ('masters', 'masters'), ('diploma' , 'diploma'), ('PhD', 'PhD'), ) pro_type = models.CharField(default = 'honours', max_length=7, choices=TYPE_CHOICES, verbose_name='type') class Meta: db_table = 'tbl_program' verbose_name_plural = "Program" def __str__(self): return self.pro_name -
How to fetch the data from an API?
I want to fetch the data from an API. Let's consider the route be "https://api.rikesh.com/posts". Method: GET How to create an API view to fetch the data from the link and display a JSON object as a response in Django Rest Framework? Do I need to use a serializer? Kindly help me to create the views.py function. -
Django - too many values to unpack (expected 2)
I'm trying to create a custom backend where an user uses a private key and a secret key to view an API endpoint that i made uing Django Rest Framework. I already know this isn't the best in terms of security, but since the endpoint is only for viewing data (it only has the GET method) it's not a big deal here. Here is my code: class TokenMiddleware(AuthenticationMiddleware): def process_request(self, request): try: token = request.GET[TOKEN_QUERY_PUBLIC] secret = request.GET[TOKEN_QUERY_SECRET] except KeyError: raise ValidationError(detail="Missing parameter in auth") user = auth.authenticate(request, token=token, secret=secret) if user: # The token is valid. Save the user to the request and session. request.user = user auth.login(request, user) else: raise ValidationError(detail="AUTH FAILED") class TokenBackend(ModelBackend): def authenticate(self, request, token=None, secret=None): if not token: return None try: publicQuery = User.objects.get(api_keys__public=token) if publicQuery != None: privateQuery = Api_keys.objects.get(public=token, secret=secret) if privateQuery.secret == secret: return User.objects.get(username=publicQuery) else: return None else: return None except User.DoesNotExist: # A user with that token does not exist return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None And here is the Api_keys model: class Api_keys(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) public = models.CharField(max_length=30, blank=True) secret = models.CharField(max_length=30, blank=True) The problem with this code is that … -
Django not commiting to Database if response is rendered differently
I have the following code: # ... # obj creation logic # ... txt = "*BULK LIST*\n\n" for item in obj_list: txt += f"*Label*: {item.label}\n*Item Code*: {item.id}\n*Date Created*: {item.created_date}\n\n" txt += "========================\n\n" # Line with issue return http.HttpResponse( txt, content_type="text/plain" ) The objects in obj_list are only saved to database if the response is returned as shown above. Now, i've been reviewing my code on this project and this part was just too dirty, so I created a template PROJECT_ROOT/templates/bulk_view.html so that presentation will be handled separately in there. Here is the tiny change I made: # same object creation logic as above, removed 'txt' and the forloop concatenating the strings for presantation. # change made on the returned response return http.HttpResponse( render(self.request, "bulk_view.html", {"items": obj_list}) ) The items render correctly, with their ids implying they have been saved to the database. But that's not what's happening. They are not in the database, and also, the id increments on each save(). I'm using Django 3.1 and Postgres 12.4 -
Ecommerce Admin panel and Api in Django
I have an urgent task where I need a Custom made Ecommerce Admin panel and API written in Django language, it is intended to be used for developing an Ecommerce mobile application. I would be glad if you could share link or any useful material concerning it. Thanks in anticipation -
Should I split my Django and DRF project into separate projects?
I am currently at the planning stage of an app that will consist of standard Django part for supervisors that can perform all CRUD operations on employee users mostly add, delete and view statistics - viewed in browser (no frontend framework just using Djangos server side rendering), two step email authentication on each login, session based auth DRF part for employees - API connected to mobile app, authentication based on device ID. (no username, or password) DRF part for clients to contact the supervisors if employees do something wrong - Token or JWT based authentication using passcode delivered by mail. I am not used to splitting Django projects into multiple sub-projects (or using same database for different projects) but it feels like every part of the project should be a standalone app due to different authentication type and the fact of simultaniousily using DRF with standard Django Can anyone who had similar problem or has some experience, advise what should I do considering different authentications and overall different user types in this project? What would be pros and cons of going into solo or multiple projects? Thanks in advance! -
The password field is not reacting based on the class attibute i passed in the widget , In django form.py file,
The username and email field are taking the class which i gave , but the password field is not taking the form-control class i gave i am using the "UserCreationForm" from django.contrib.auth.form and the "User" model from the djano.contrib.auth.model widgets = { 'username': TextInput(attrs={'class':'form-control'}), 'email': TextInput(attrs={'class':'form-control'}), 'password1': PasswordInput(attrs={'class':'form-control'}), 'password2': PasswordInput(attrs={'class':'form-control'}), } [This is the output i am getting but i need the password fields to be responsive with the 'form control' class][1] [1]: https://i.stack.imgur.com/McJ8J.png -
How to fix “ '" is not a valid UUID.”
I want to let user re-order/sort table of content with drag and drop. And whene I push "Submit order" button (after re-order) I have error: ''' ValidationError at /save-group-ordering/ ['“” is not a valid UUID.'] Request Method: POST Request URL: http://127.0.0.1:8000/save-group-ordering/ Django Version: 3.0.2 Exception Type: ValidationError Exception Value: ['“” is not a valid UUID.'] ''' I only start work with django and I not understand what I am doing wrong. Here is my models.py ''' class Task(models.Model): project = models.ForeignKey(Project, null=True, on_delete=models.CASCADE) title = models.CharField(max_length=300, null=True) complete = models.BooleanField(default=False) deadline = models.DateField('Deadline of the task (year, month, day)', default=date.today) created = models.DateTimeField(auto_now_add=True,null=True) lookup_id = models.UUIDField(default=uuid.uuid4, editable=False, db_index=True) order = models.IntegerField(blank=False, default=100_000) def __str__(self): return self.title def deadline_func(self): days = self.deadline - date.today() return days ''' Here is my urls.py ''' from django.urls import path from . import views urlpatterns = [ path('' , views.projects_list, name="list"), path('create_project/' , views.createProject, name="create_project"), path('deadline_project/<str:pk>' , views.deadlineProject, name="deadline_project"), path('update_project/<str:pk>' , views.updateProject, name="update_project"), path('delete_project/<str:pk>' , views.deleteProject, name="delete_project"), path('create_task/<str:pk>' , views.createTask, name="create_task"), path('save-group-ordering/', views.save_new_ordering, name='save-group-oldering'), path('deadline_task/<str:pk>' , views.deadlineTask, name="deadline_task"), path('update_task/<str:pk>' , views.updateTask, name="update_task"), path('delete_task/<str:pk>' , views.deleteTask, name="delete_task"), ] ''' Here is my views.py ''' @require_POST def save_new_ordering(request): form = OrderingForm(request.POST) if form.is_valid(): ordered_ids = form.cleaned_data["ordering"].split(',') with … -
Setting up apache2 on lightsail (AWS)
whenever i run the following lines on a Linux terminal, after configuring my config files for wsgi sudo service apache2 restart I get the following error: ob for apache2.service failed because the control process exited with error code. See "systemctl status apache2.service" and "journalctl -xe" for details. On running journalctl -xe, I get: Oct 24 06:08:07 ip-172-26-12-135 dhclient[428]: XMT: Solicit on eth0, interval 119120ms. Oct 24 06:08:25 ip-172-26-12-135 sudo[24683]: bitnami : TTY=pts/0 ; PWD=/opt/bitnami/projects/PROJECT/PROJECT ; USER=root ; COMMAND=/usr/sbin/service apache2 restart Oct 24 06:08:25 ip-172-26-12-135 sudo[24683]: pam_unix(sudo:session): session opened for user root by bitnami(uid=0) Oct 24 06:08:25 ip-172-26-12-135 systemd[1]: Starting The Apache HTTP Server... -- Subject: A start job for unit apache2.service has begun execution -- Defined-By: systemd -- Support: https://www.debian.org/support -- -- A start job for unit apache2.service has begun execution. -- -- The job identifier is 9535. Oct 24 06:08:26 ip-172-26-12-135 apachectl[24689]: apache2: Syntax error on line 225 of /etc/apache2/apache2.conf: Syntax error on line 45 of /etc/apache2/sites-enabled/dj Oct 24 06:08:26 ip-172-26-12-135 apachectl[24689]: Action 'start' failed. Oct 24 06:08:26 ip-172-26-12-135 apachectl[24689]: The Apache error log may have more information. Oct 24 06:08:26 ip-172-26-12-135 systemd[1]: apache2.service: Control process exited, code=exited, status=1/FAILURE -- Subject: Unit process exited -- Defined-By: systemd -- Support: … -
Django: Count and Sum items in the same item_category within a queryset
It seems this should be fairly simple, but i'm stuck. I'm trying to Count and Sum items in the same item_category within a queryset. views.py #counting data = AllData.objects.values('item','item_category').annotate(item_count=Count('item'),item_category_count=Count('item_category')) print("Data",data) produces: Data <QuerySet [{'item': 'Item1', 'item_category': 'Sport', 'item_count': 15, 'item_category_count': 15)},{'item': 'Item2', 'item_category': 'Leisure', 'item_count': 12, 'item_category_count': 12)},{'item': 'Item3', 'item_category': 'Sport', 'item_count': 10, 'item_category_count': 10)},]> The item_counts are ok, but the output i'm looking for needs to Sum the the number of items in the similar category. Something like this: data = AllData.objects.values('item','item_category').annotate(item_count=Count('item'),item_category_count=Sum(Count('item_category'))) But this produces an error: Cannot compute Sum('Count'): 'Count' is an aggregate The results i'm looking for should look like this: Data <QuerySet [{'item': 'Item1', 'item_category': 'Sport', 'item_count': 15, 'item_category_count': 25)},{'item': 'Item2', 'item_category': 'Leisure', 'item_count': 12, 'item_category_count': 12)},{'item': 'Item3', 'item_category': 'Sport', 'item_count': 10, 'item_category_count': 25)},]> Here, the number of items in the 'Sport' category has been summed as 10+15 to produce 'item_category_count': 25 Thanks -
Elastic Beanstalk-Django: 500 deploy Internal Server Error
My questions might similar to other stackoverflow's questions. I have tired every single questions' solutions but none of them did not work. I have created simple Django app and it works locally fine. My app structure like this: . This my .ebextensions django.config. option_settings: aws:elasticbeanstalk:container:python: WSGIPath: DjangoElasticbeanstalkdeploy/wsgi.py I have used default_platform: Python 3.6 running on 64bit Amazon Linux. My environment Heath looks good. Everything looks ok to me but when I click the url I am getting this error. -
How to allow a form to submit, but prevent blank fields from being saved using Django Admin?
I am using Django Admin, and have a model like this: class Item(models.Model): id = models.CharField(max_length=14, primary_key=True) otherId = models.CharField(max_length=2084, blank=True) I want id to be required and unique, and I want otherId to be optional on the Admin form, but if otherId is provided, it has to be unique. The problem I am running into is, whenever I create an instance of Item using the Admin form and I do not provide an otherId, Django tries to save the otherId field as a blank value, but this means the second time I try to save an instance with a blank otherId value it violates the column's unique constraint and fails. I need Django to check if the otherId field is falsey before saving, and if it is falsey, do not save that empty value along with the model. Is this possible? -
Django update model fields after a certain time
I have a Assignment model, which has the following attributes for now: title (char Field), deadline(date and time field), closed (boolean field). The closed field denotes if the assignment is past deadline or not. The closed field is false by default. So now, what I want is that, when an object of the model is created the closed field should be updated automatically on the basis of the deadline. Say the deadline is after 2 hours. Then the closed field should become true after 2 hours. What is the best way to do this? Does Django provide any field of this type; which would update itself after a certain time?