Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django jsonresponse returns empty values
class HomeView(TemplateView): template_name = 'pbi_theme_app/index.html' def get(self, request): form = HomeForm() position = Legend.objects.filter(selection="Position") return render(request, self.template_name, {'form': form, 'sss': position}) def post(self, request): text = '' show = '' position = '' form = HomeForm(request.POST) if form.is_valid(): text = form.cleaned_data['post'] self.text = form.save() show = form.cleaned_data['show'] #position = Legend.objects.filter(selection="Position").values() position = form.cleaned_data['position'] return JsonResponse({'text': text, 'show': show, 'sss': position}) I am trying to push the response that I get from POST form to json, but the value in the dictionary is empty, the form doesn't save it somehow. {"text": "", "show": "", "sss": ""} It was working before, but then I've started encountering error that the variables like "text" were defined, so I've put there just an empty string, which now passes into the dictionary, not the forms' real data. Thank you. -
Attribute error, with exception value: safe
After adding to the model save function, attribute error occurs with exception value = 'self'. Code: from django.db import models from djmoney.models.fields import MoneyField from PIL import Image class Item(models.Model): title = models.CharField(max_length=150) price = MoneyField( decimal_places=2, default=0, default_currency='USD', max_digits=11, ) image = models.ImageField(upload_to='pictures', default='static/images/man.png') def save(self): super().save() img = Image.open(self.image.path) if img.height > 350 or img.width > 350: new_img = (350, 350) img.thumbnail(new_img) img.self(self.image.path) -
Using class in Python/Django testing to make code more reusable
I need some help with my testing architecture. My code works but it seems ugly for me. Could you take a look : The goal is to make the same tests for all my pages in Django : I wrote a unit testing.py from django.urls import reverse, resolve class SinglePageTest(object): str_reverse = '' adresse = '' template = None template_path = '' str_contain = '' def initialize(self): self.url = reverse(self.str_reverse) self.view = resolve(self.adresse) self.response = self.client.get(self.url) def test_status_200(self): self.assertEqual(self.response.status_code, 200) def test_templates_home(self): self.assertTemplateUsed(self.response, self.template_path) def test_contains_HTML(self): self.assertContains(self.response, self.str_contain) def test_url_resolve(self): self.assertEqual(self.view.func.__name__, self.template.as_view().__name__) When I need to test a page in test.py I do this : from django.test import TestCase, SimpleTestCase from DjangoTools.testing import SinglePageTest class RetrievePassword(SimpleTestCase, SinglePageTest): def setUp(self): self.str_reverse = 'retrieve-password' self.adresse = '/accounts/retrieve-password' self.template = RetrievePasswordView self.template_path = 'accounts/retrieve-password.html' self.str_contain = '<h1>🔑 Récupérer le <span class="clr-org">mot de passe</span></h1>' super(RetrievePassword, self).setUp() SinglePageTest.initialize(self) The problem is that PyCharm doesn't find the reference for a lot of method in testing.py and that's normal cause I'am using a basic object that doesn't contains these methods. My questions are : Is-it well to do like this ? Can I say that I'm using Mixins ? How to tell pycharm to find assertTemplateUsed, client.get … -
How to get only the base model instances from query?
Hopefully my question won't have been asked before. I've the following models in my Django app: from django.db import models class A(models.Model): some_attribute = models.SomeField() def some_method(self): do_stuff() # Note: not abstract class B(A): def some_other_method(self): do_other_stuff() Now, if I have one A and one B in the database, when I issue a A.objects.filter() call, I get the A and also the B instance (as expected). But what if I in fact only want the instances of A specifically? I don't see how to write is as an .exclude() instruction. Could filtering with type == "A" be the intended way? -
Get serializer fields in RelatedField serializer django rest
class ScreenCategorySerializer(serializers.ModelSerializer): screen = ScreenListingField(many=True, read_only=True) class Meta: model = ScreenCategory fields = ['id', 'title', 'screen', 'active', 'position'] class ScreenListingField(serializers.RelatedField): def to_representation(self, value): res = {} res['id'] = value.id res['title'] = value.title res['layout'] = value.layout res['project'] = value.project.id res['last_change'] = value.last_change res['width'] = value.width res['height'] = value.height res['background_color'] = value.background_color if value.constant_color is None: res['constant_color'] = None else: res['constant_color'] = value.constant_color.id res['styles'] = value.styles res['base'] = value.base return res I have the following serializer, inside the ScreenListingField I would like to get the id of the ScreenCategory. How can I get it? -
how to pass data from multiple checkboxes created in django template using for loop to views.py without using forms
This is my html form in which i have a text field for a word and i am running a for loop which created checkbox for the list of document a user has and displays it as form. <body> <form id="form" method = "POST"> {% csrf_token %} <fieldset id="User"> <legend>Your details:</legend> <p><label for="word">Enter your word</label> <input type="text" id="word" name="word"> </p> {% for doc in docs %} <p> <input type="checkbox" id="{{ doc.document_id }}" name="docid" value="{{ doc.path }}"> <label for="{{ doc.document_id }}"> {{ doc.document_name }} </label><br> </p> {% endfor%} <input type="submit" value="Submit" > </fieldset> </form> </body> In views.py I have below method which loads this html page def client_home(request): client_pr = Client_Profile.objects.get(user_id=request.user) events = Event.objects.filter(client_id=client_pr.pk) name = request.POST.get('word') id = request.POST.get('docid') print(name) print(id) docs = [] for eve in events: docs = Document.objects.filter(event_id=eve) context = {'events': events, 'docs': docs} return render(request, 'Elasticsearch/form.html', context) My question is as i am using a for loop create checkbox field based on number of documents a user has and when I try to print them in my Views.py file it is only priniting last document id whose checkbox is created and not all the documents. -
If and else don't save into None
I am a student who is learning Django. Although Views.py was created as follows, there is a problem that the else part of join_detail is not saved in the DB. There is no error and it is not saved at all. Which part is the problem? I attach the full code of views.py and some code that has a problem. def join_create(request, id): current_category = None designated = Designated.objects.all() designated_object = Designated.objects.filter(rep_price='True') value_p = Value.extra_cost element = Element.objects.all() value_object = Value.objects.all() categories = Category.objects.all() products = Product.objects.all() if not request.user.is_authenticated: return HttpResponseRedirect(reverse('zeronine:login')) if request.method == "POST": product = Product.objects.get(product_code=id) join = Join() join.product_code = product join.username = request.user join.save() if request.method == "POST": form = ElementForm(request.POST) if form.is_valid(): for value_code2 in request.POST.getlist('value_code2'): element = Element() element.designated_code = Designated.objects.get(product_code=id) element.value_code = get_object_or_404(Value, pk=value_code2) element.save() else: element = Element() element.designated_code = Designated.objects.get(product_code=id) element.value_code = None element.save() if request.method == "POST": form = JoinDetailForm(request.POST) if form.is_valid(): for quantity, price2, value_code2 in zip(request.POST.getlist('quantity'),request.POST.getlist('price2'),request.POST.getlist('value_code2')): join_detail = JoinDetail() join_detail.join_code = join join_detail.designated_code = Designated.objects.get(product_code=id) join_detail.value_code = get_object_or_404(Value, pk=value_code2) join_detail.quantity = quantity join_detail.price = price2 join_detail.save() else: for quantity, price2 in zip(request.POST.getlist('quantity'),request.POST.getlist('price2')): join_detail = JoinDetail() join_detail.join_code = join join_detail.designated_code = Designated.objects.get(product_code=id) join_detail.value_code = None join_detail.quantity = quantity … -
Template does not exist for django authentication views
Django newbie here. I am just trying to make a password change form using Django authentication system. I used my own views for login and logout functionality. I read the docs and for password change form as mentioned, I made a registration folder inside my templates directory and made a template html file named password_change_form.html , but when I go to the url http://127.0.0.1:8000/accounts/password_change , I keep getting the error TemplateDoesNotExist at /accounts/login/ . Here is my app structure: and my urls.py file: from django.urls import path,include from django.contrib.auth import views as auth_views from . import views urlpatterns = [ path('',views.home_page,name='home_page'), path('register',views.registration_view,name='registration_view'), path('login',views.login_view,name='login_view'), path('logout',views.logout_view,name='logout_view'), path('accounts/',include('django.contrib.auth.urls')), ] What and why is this happening? Please help. I would appreciate it. -
django admin gives error when trying to access a certain model
I'm making a web page that for the purposes of this question, we can say it has 2 models. a User model and an Order model. Users log in and order what they want. the Order model has a foreign key referencing the User model. and ifI try to order something, specifically if I try to give the userID field of the Order model some value, it works just fine, or at least seems like it. Then when I try to look at the list of orders in the admin page I get the following Error: ValueError at /admin/dashboard/order/ invalid literal for int() with base 10: b'22 11:28:34.566846' and this is the whole traceback: Environment: Request Method: GET Request URL: http://localhost:8000/admin/dashboard/order/ Django Version: 3.2.5 Python Version: 3.9.6 Installed Applications: ['mainpage', 'regpage', 'loginpage', 'dashboard', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\Mohsen\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Mohsen\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Mohsen\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\admin\options.py", line 616, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "C:\Users\Mohsen\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:\Users\Mohsen\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response … -
Django filtering on DateTimeField extremely slow
Environment AWS RDS t3.micro (2 vCPUs, 1GiB RAM) PostgreSQL 11.10 I have more than 15 million records of Note, the model of which is like: class Note(models.Model): ... post_date = models.DateTimeField() ... FYI, Note has 35+ fields, some of which are ManyToManyField and ForeignKey fields. Problem start_time = time.time() queryset = Note.objects.filter( # post_date=datetime.now() - timedelta(days=6), post_date__year=2021, post_date__month__gt=7, )[:100] tmp = list(queryset) print("Time elapsed: ", time.time() - start_time) The code above takes just 0.68 seconds, but if I uncomment # postTs=datetime.now() - timedelta(days=6), the time increases to 55.53 seconds. To mitigate this issue I'm considering converting the DateTimeField to PositiveIntegerField for storing timestamp values instead. Before taking that step, is there anything else that I can try? Why is this happening? -
Django: Problem deleting many-to-many database objects when the are connected with a through-table
Django produces an error that I cannot delete a composer object that used to be related to a spotifyartist object through a custom through table. My Django app is called 'music' and I'm using mysql/mariadb as the database The error Django produces when deleting a composer object is: IntegrityError at /admin/music/composer/(1451, 'Cannot delete or update a parent row: a foreign key constraint fails (bladmuziek.music_composer_spot_artist, CONSTRAINT music_composer_spot__composer_id_4d30a8de_fk_music_com FOREIGN KEY (composer_id) REFERENCES music_composer (id))') Even after I delete the entry in the through-table for the composer + Spotify artist pair, and there is no obvious connection (to me) any more between the two model objects, I still cannot delete a (previously connected) composer or Spotify artist object. I cannot figure out how I seem to violate the constraint that the error message talks about. I guess I don't fully understand the error message, and do not know for sure if it has to do with the constraint that I added in the through model or it if is some other constraint. Any suggestions on how to fully understand the error message and delete the Django object are appreciated. The relevant snippets of my code are the composer model, the spotifyartist model, and … -
order by with field that is not in group by fields django orm
final_submission: the submission which has the maximum score. I want query which gives me a list of final submissions for each problem and participant that is sorted with submitted time. Submission.objects.all().values('participant_id', 'problem_id').annotate(Max('score')).order_by('-submitted_time') above query does not work. I don't know how to order by with a field that is not in group by fields -
Django logger file setup failure
I am trying to set up the logger but getting the following error on my production env. Same settings are working on my dev env, can someone please point out the issue. Following are my settings -
Multiple image in one queryset Django
How to add multiple images within one django queryset that will have a image field? It can be done through foreignkey but if i use different table for image then id's will be generated differently Can anyone help me on how exactly i can upload multiple images on one django queryset? Example: We can upload multiple images in one post Facebook -
How can I pass two queryset on the same page?? (django rest framework and react)
I want to show two queryset value in the same url. I have my homepage where I am passing all products list and after that section on the same page I am trying to show product based on category like this first recent products then next section all bikes(based on category). @api_view(['GET']) def getProducts(request): products = Product.objects.all() p = Product.objects.all().filter(category = 1) context = { "request": request, } first_serializer = ProductSerializer(products, many= True, context=context) second_serializer = ProductSerializer(p, many= True, context=context) response = first_serializer.data + second_serializer.data return Response(response) this is my react page Recent Products {loading ? <Loader /> : error ? <Message variant='danger'>{error}</Message> : <Row> {products.map(product => ( <Col key={product._id} sm={12} md={6} lg={4} xl={3}> <Product product={product} /> </Col> ))} </Row> } I want the same procedure like this <Row> {p.map((product) => ( <Col key={product._id} sm={12} md={6} lg={4} xl={3}> <Product product={product} /> </Col> ))} </Row> <Row> but I couldn't able to map the p object. what should I do now? I am using react with redux. -
Django Herkou deployment retuning Application Error
I'm stuck in a loop of problems with running my django app on heroku. I previously had an Internal Error message though i have fixed that. Now i'm facing with an Application Error and don't seem to understand why? I've included the heroku log below: `` 2021-08-22T05:06:17.059556+00:00 app[web.1]: self.load_wsgi() 2021-08-22T05:06:17.059556+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi 2021-08-22T05:06:17.059557+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2021-08-22T05:06:17.059557+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/base.py", line 67, in wsgi 2021-08-22T05:06:17.059557+00:00 app[web.1]: self.callable = self.load() 2021-08-22T05:06:17.059557+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 58, in load 2021-08-22T05:06:17.059558+00:00 app[web.1]: return self.load_wsgiapp() 2021-08-22T05:06:17.059558+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp 2021-08-22T05:06:17.059558+00:00 app[web.1]: return util.import_app(self.app_uri) 2021-08-22T05:06:17.059558+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/util.py", line 359, in import_app 2021-08-22T05:06:17.059559+00:00 app[web.1]: mod = importlib.import_module(module) 2021-08-22T05:06:17.059559+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/importlib/init.py", line 127, in import_module 2021-08-22T05:06:17.059559+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2021-08-22T05:06:17.059559+00:00 app[web.1]: File "", line 1030, in _gcd_import 2021-08-22T05:06:17.059560+00:00 app[web.1]: File "", line 1007, in _find_and_load 2021-08-22T05:06:17.059560+00:00 app[web.1]: File "", line 986, in _find_and_load_unlocked 2021-08-22T05:06:17.059560+00:00 app[web.1]: File "", line 680, in _load_unlocked 2021-08-22T05:06:17.059560+00:00 app[web.1]: File "", line 850, in exec_module 2021-08-22T05:06:17.059560+00:00 app[web.1]: File "", line 228, in _call_with_frames_removed 2021-08-22T05:06:17.059561+00:00 app[web.1]: File "/app/server/plur/wsgi.py", line 16, in 2021-08-22T05:06:17.059561+00:00 app[web.1]: application = get_wsgi_application() 2021-08-22T05:06:17.059561+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application 2021-08-22T05:06:17.059561+00:00 app[web.1]: return WSGIHandler() 2021-08-22T05:06:17.059573+00:00 app[web.1]: … -
Django - How to combine Authen middleware and my custom middleware?
I have an api that require Token in headers and users must have role is_staff to process. Here is my model.py to clarify about is_staff role class User(AbstractBaseUser, PermissionsMixin): """Custom user model that support using email instead of username""" email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_employee = models.BooleanField(default=True) objects = UserManager() USERNAME_FIELD = 'email' Here is the api in my views.py class get_user_info_from_token(generics.GenericAPIView): permission_classes = (IsAuthenticated, ) def get(self, request): """ I put the below rows in middleware User = Token.objects.get(key = request.auth).user if User.is_staff: """ return HttpResponse("You are staff) Here is my middleware: class CustomMiddlware(object): ... def __call__(self, request): token = request.headers['Authorization'][6:] user = Token.objects.get(key=token).user if user.is_staff: response = self.get_response(request) else: return HttpResponseForbidden("You are not allowed") ... Well I have 2 questions: 1/ I want to put permission_classes = (IsAuthenticated, ) into my middlware to simplyfy my code. But I do not know how to do it. 2/ Moreover, in my middleware, I can not run User = Token.objects.get(key = request.auth).user since I got this error AttributeError: 'WSGIRequest' object has no attribute 'auth'. -
How to update models using model forms in django
I tried updating through model form but i am getting error this field required for all fields after submitting the form below is my update view enter code here def update_data(request, id): if request.method == 'POST': print("in post request form submitted") pi = User.objects.get(pk=id) frm = StudentRegistration(request.POST, instance=pi) print("going for form validation") if frm.is_valid(): print("form valid") frm.save() else: pi = User.objects.get(pk=id) frm = StudentRegistration(instance=pi) print("first request get") return render(request, 'enroll/updatestudent.html', {'form':frm} [output screen][1] above is my update view but my data is not updated im getting error field required after clicking submit please guide -
Can a Django ModelForm save multiple new models on a single submit?
I am learning Django and building a website to save and display cafeteria food offerings. I have a Model Meal and another FoodItem, where multiple FoodItems are children of a Meal. class Meal(models.Model): date = models.DateField(default=datetime.date.today) BFAST = 0 LUNCH = 1 DIN = 2 MEAL_TIME_CHOICES = [ (BFAST, 'Breakfast'), (LUNCH, 'Lunch'), (DIN, 'Dinner'), ] meal_time = models.IntegerField( choices = MEAL_TIME_CHOICES, default = MEAL_TIME_CHOICES[0] ) class FoodItem(models.Model): meal = models.ForeignKey(Meal, on_delete=models.CASCADE) name = models.CharField(max_length=80) I'd like to create a ModelForm that has multiple textinputs for FoodItems so that multiple foods can be saved and associated with the same meal on a single submission of the form. My attempt right now only allows me to submit a single food item at a time. class FoodItemForm(forms.ModelForm): class Meta: model = FoodItem fields = ('name',) Any assistance in doing this the correct way would be much appreciated! -
Can not switch from assigning permission_classes to use decorator @permission_classes
The below is an api that required authen. It works class some_random_api(generics.GenericAPIView): permission_classes = (IsAuthenticated, ) def get(self,request): return HttpResponse("Called successfully") However, I dont like declaring variable. After looking up this document, https://www.django-rest-framework.org/api-guide/permissions/ . I find an alternative way by using decorator. So I change my code into this. from rest_framework.decorators import permission_classes class some_random_api(generics.GenericAPIView): @permission_classes(IsAuthenticated) def get(self,request): return HttpResponse("You call random test api") Now this API does not check Authen -
should Stripe be integrated in frontend or backend ? (React+Django Rest )
just a bit confused as i found both solutions after a day of research. some suggest to use "pip install dj-stripe" and add keys and other options in "settings.py". Then the script in frontend to get redirect button and some suggest the use of "npm install --save @stripe/react-stripe-js @stripe/stripe-js", and add keys in "app.js" or a designated js file. i would like to know if it differs (security ,efficiency,.. wise), or is there a concrete way of doing it (best practice way), thank you. -
How to get a value from one method to another within a model observer
Here is an example from the filtering model observer: class MyConsumer(GenericAsyncAPIConsumer): ... @action() async def subscribe_to_comment_activity(self, user_pk, **kwargs): # We will check if the user is authenticated for subscribing. user = await database_sync_to_async(User.objects.get)(pk=user_pk) await self.comment_activity.subscribe(user=user) I want to do some filtering, but that is only possible for my case if I have the instance at hand to filter against. That means as I see it, I need the user=user value in the observer serializer method. @comment_activity.serializer def comment_activity(self, instance: Comment, action, **kwargs) -> CommentSerializer: '''This will return the comment serializer''' return CommentSerializer(instance) And here comes my question then, how can I get the user value in the model serializer method? -
django channels: updates to the data base deletes older data from the same session on the socket
So I'm building a tic tac toe game which you can play online, but I wanted to save the win / lose count of each user and I'm using django 3.2 ,channels 3 and channels_presence with python 3.9 I've built the socket and the client successfully and now you can play as much games as you would like... I think The problem is that the score I try to save get stored in the data base but after another game the score returns back to zero so if two users are playing in a room and user 1 won 2 games the score would get updated then if the other user won a game his score would be 1 and the user 1 score would be reset to zero My User model class CustomUser(AbstractUser): won_games = models.IntegerField(default=0) lost_games = models.IntegerField(default=0) draw_games = models.IntegerField(default=0) def win(self): self.won_games += 1 self.save() def lose(self): self.lost_games += 1 self.save() def draw(self): self.draw_games += 1 self.save() I've put this into the receive function in my consumers.py if text_data['type'] == 'completed': self_channel = Presence.objects.get(channel_name=self.channel_name) competitor = self_channel.room.presence_set.filter(~Q(channel_name=self_channel)).first().user competitor = CustomUser.objects.get(email=competitor.email) user = self.scope['user'] print(user.email, competitor.email) if competitor: competitor.win() if user.is_authenticated: user.lose() return **Note: **I'm relying on … -
How do disable redirecting when I clicking on a button? Django
I am trying to create a like button for my page. thats okey its working but when I click the button page is refreshing. When I click on the like button, I want the counter showing the number of likes to increase. I try used Ajax but I failed. here are my codes.. Views: def liked_post(request,pk): post =get_object_or_404(UserPosts, id=request.POST.get("userposts_id")) liked = False if post.like_post.filter(id = request.user.id).exists(): post.like_post.remove(request.user) liked = False else: post.like_post.add(request.user) liked = True return HttpResponseRedirect(reverse('detail', args=[str(pk)] )) def detail_post(request,_detail): postDetail = UserPosts.objects.get(pk = _detail) liked = False if postDetail.like_post.filter(id= request.user.id).exists(): liked = True context= { "detail":postDetail, "liked":liked } return render(request,"DetailPost.html",context) Javascript file: $(document).ready(function () { //like ajax call $('.like-form').submit(function (e) { e.preventDefault(); const userposts_id = $('.like-btn').val(); const token = $('input[name=csrfmiddlewaretoken]').val(); const url = $(this).attr('action') $.ajax({ method: "POST", url: url, headers: { 'X-CSRFToken': token }, data: { 'userposts_id': userposts_id } }) }) }) Template: <form class="btn-group mt-1 like-form" action="{% url 'like_post' detail.pk %}" method="POST"> {% csrf_token %} {% if request.user.is_authenticated %} {% if detail.username_id == request.user.id %} <button class="btn btn-primary btn-sm" disabled>Like</button> {% else %} {% if liked %} <button class="btn btn-danger btn-sm " type="submit" name="userposts_id" value="{{ detail.id }}">Unlike</button> {% else %} <button class="btn btn-primary btn-sm like-btn" type="submit" name="userposts_id" … -
Django: Update field in Model when condition is met
I have a Post Model that looks like the following. When the expired timestamp is less than the now timestamp I would like the status to change from Live to Expired however the code does not seem to update when the condition is met. How can I change this so it does update class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=60) topic = models.CharField(choices=TOPIC_CHOICES, max_length=60) content = models.TextField(max_length=1500) likes = models.ManyToManyField(User, related_name="posts_likes", blank=True, through=PostLike) dislikes = models.ManyToManyField(User, related_name="post_dislikes", blank=True, through=PostDislike) # comments = models.CharField(max_length=240, null=True, blank=True) created_timestamp = models.DateTimeField(default=now, editable=False) expired_timestamp = models.DateTimeField(default=expiration_time, editable=False) status = models.CharField(max_length=60, default="Live") def save(self, *args, **kwargs): if now >= self.expired_timestamp: self.status = "Expired" super(Post, self).save(*args, **kwargs)