Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Models Exercise
Im new using django models, so I started doing some practice exercises that a friend did to me. But I got stuck 😅, this is the problem that I wanted to solve. Requirement: A Game company requires a solution which allow them store next information in the best way possible: server: Field which correspond to server's name and is representated as a slug name(ie: korea as kr, europe as eu, etc) game_id: Unique field which correspond to a game identifier and is representated as a integer (ie: 8234, 7324, etc) game_data: Field which contains all information of the determinated game_id stored in JSON format. Relationships: Server has many game_Id. Game_id has only a single game_data. To Consider: Game_id is an unique field, but into differents servers. By the momment, this is my code. models.py class Game(BaseModel): server = models.ForeignKey(Server, on_delete=models.CASCADE) game_id = models.CharField("gameId", max_length=25) game_data = JSONField(blank=True, False=True) class Server(BaseModel): name = models.SlugField("server", unique=True, max_length=25) I could said It works "well", but I've still having troubles about repeated game_ids on determinated servers, because my code it always will save all data without consider anything about server field. I tried to set unique = True on game_id field, but that validation … -
Auto foreign key in django models
It is possible to do this in Django. I have models and I want every new user to register in Model User and automatically in models Customer in foreign key register class Customer(models.Model): here auto user = models.ForeignKey(User, on_delete=models.CASCADE) phone = models.CharField(max_length=11,null=True) likecus=models.ManyToManyField(smartphone ,verbose_name="b",null=True) def __str__(self): return "User: {}, phone: {}".format(self.user, self.phone) -
My serializer that returns a 0 for Null value is not working
I'm trying to create a serializer that returns the value 0 instead of Null when API data is requested. class MyIntegerField(serializers.IntegerField): def to_representation(self, value): if value is None: return 0 return super(MyIntegerField, self).to_representation(value) class ListSerializer(serializers.ModelSerializer): post_count = MyIntegerField(initial=0) class Meta: model = Post fields = (..., 'post_count', ...) model.py: post_count = models.IntegerField(blank=True, null=True) If a user has no posts, then I would like to return the value 0, instead of Null. What is the issue with my current serializer? I think the field that's inputted is still pulling from my model field, and not the new serializer function. Currently I'm still receiving a Null when user requests data. -
Django API test not working for post request.with payload
I am writing some test for an API that I am working on. I am quit new to Django Rest-framework. This is the code for my 'create' test. The strange thing is that my test is failing (BAD request 400) but my published reat-api is working, at least via the django api-web-browser. I can't find the mistake. Can anyone see what I am doing wrong? The Vacancy_url is correct, I checked that by printing in in code. The get request don't have any problems. So I can conclude that my client is working. Then I thought it must the payload That I am sending. Here I show my test script and my model and view. TESTSCRIPT: from django.contrib.auth import get_user_model from django.urls import reverse from django.test import TestCase from rest_framework import status from rest_framework.test import APIClient from core.models import Vacancy from vacancy.serializers import VacancySerializer VACANCY_URL = reverse('vacancy:vacancy-list') class PrivateVacanciesApiTests(TestCase): """ Test the Private vacancy API""" def setUp(self): self.client = APIClient() self.user = get_user_model().objects.create_user( email='test@uxstudio.nl', password='testpass') self.client.force_authenticate(self.user) def test_create_vacancy_successful(self): """Test create a new vacancy""" payload = { "title": "titel", "description": "wat tekst om te testen", "is_active": True, } self.client.post(VACANCY_URL, payload) exists = Vacancy.objects.filter( company_id=self.user, title=payload['title'] ).exists() self.assertTrue(exists) MODEL class Vacancy(models.Model): """Vacancy … -
passing dictionary to view ,with multiple key:value pairs
def status_(request,id): stages=['Vendor Quotation','Estimate Generation','Purchase Requsition','Purchase Order','Provision To Invoice','Reimbursement Invoice','Request Receipt#(PTI+RI+PO)','Receipt# Received(Updated PTI)','Request Sales Tax Invoice','Uploaded to Jazz Portal'] ctx={'invoice':Invoices.objects.get(pk=id),'stages':stages} return render(request,"Invoices/status.html",ctx) Hi I am trying to pass multiple objects of data for displaying to the template for displaying , I am creating a ctx dictionary with multiple 2 key value pairs ,second Key-value pair is array ,when i access this array in by using {% for idx in range(0,len(ctx.get("stages")) %} I get following parsing error **Could not parse the remainder: '(0,len(ctx.get("stages"))' from 'range(0,len(ctx.get("stages"))'** -
stderr + python: can't open file 'app.py': [Errno 2] No such file or directory using spawn in electron js
stderr + python: can't open file 'app.py': [Errno 2] No such file or directory using spawn in electron js please someone helps me -
Django Rest Views: How to access a class variable in another class?
Here's how my authentication works: I get an email and check if that email exists in the database, if it doesn't, I generate a random 8-digit number and then email it to the entered email address and inform the user to confirm his/her email address by entering the emailed code. Here's the View: class CheckEmailView(APIView): permission_classes = [AllowAny] def post(self, request, *args, **kwargs): serializer = CheckEmailSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = Account.objects.filter(email=serializer.data['email']) if user.exists(): return Response({'is_member': True}) else: confirm_code = randint(10000000, 99999999) context_data = {'code': confirm_code} email_template = get_template('email.html').render(context_data) email = EmailMessage( 'Confirm Email', email_template, settings.EMAIL_HOST_USER, [serializer.data['email']], ) email.content_subtype = 'html' email.send(fail_silently=False) return Response({'is_member': False}) I'm using another View to check if the user enters the correct confirmation code, so now I have to send the value of confirm_code variable to the new class. which Looks like this at the moment: class ConfirmEmailView(APIView): permission_classes = [AllowAny] def post(self, request, *args, **kwargs): user_input_code = request.data print(confirm_code) return Response(True) But I have no idea how to pass the value from CheckEmailView to ConfirmEmailView class. I'm new to Django so despite the solution, any tips on how to make my code any better or any faster or more logical solution to manage this whole process … -
Django - item created by logged user ViewSet
What I want: A logged user creates an item which is stored in the database with that user ForeignKey. I have 2 codes: both should do the same thing (create item linked to current user), but one of them works and the other one doesn't. GET requests work, I'm focusing on POST requests. First code (POST working): class UserPortfolio(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=200, blank=False, null=False) slug = models.CharField(max_length=200, blank=False, null=False) class UserPortfolioSerializer(serializers.ModelSerializer): class Meta: model = UserPortfolio exclude = ('id', 'user') class UserPortfolioViewSet(viewsets.ModelViewSet): serializer_class = serializers.UserPortfolioSerializer queryset = UserPortfolio.objects.all() permission_classes = [IsAuthenticated] def get_queryset(self): return UserPortfolio.objects.filter(user=self.request.user).order_by('last_updated') def perform_create(self, serializer): serializer.save(user=self.request.user) Second code (POST not working): class ExchangeConnection(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) portfolios = models.ManyToManyField(UserPortfolio, blank=True) exchange = models.ForeignKey(Exchange, on_delete=models.CASCADE) last_updated = models.DateTimeField(auto_now=True) class Meta: db_table = 'exchange_connection' verbose_name_plural = "Exchange Connection" def __str__(self): return self.user.username class ExchangeConnectionSerializer(FlexFieldsModelSerializer): class Meta: model = ExchangeConnection fields = '__all__' expandable_fields = {'exchange': ExchangeSerializer, 'portfolios': (UserPortfolioSerializer, {'many': True})} class UserExchangeConnectionsViewSet(viewsets.ModelViewSet): serializer_class = serializers.ExchangeConnectionSerializer queryset = ExchangeConnection.objects.all() permission_classes = [IsAuthenticated] def get_queryset(self): return ExchangeConnection.objects.filter(user=self.request.user).order_by('last_updated') @action( detail=True, methods=['post'], url_path='create-exchange-connection', ) def post(self, serializer): serializer = serializers.ExchangeConnectionPostSerializer(user=self.request.user) if serializer.is_valid(): serializer.save() return Response({'status': 'Exchange created.'}) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) The error I get when I POST … -
Trouble Importing module in Django
I am working inside of a Django project and I'm trying to import a class from the models.py file. Screen shot of file scaffold shows the google_locator.py file I am trying to import Truck instance from models. I have tried .models, ..models, ../models, ./models, truck.models, and several more combinations. I either get an "invalid syntax" error or "ImportError: attempted relative import with no known parent package" -
return JsonResponse is printing it's values after Click
I am using Django Version- 3.8.1. AND i built a like, dislike system for BlogPost. BUT when i click on Like button it just print {"action": "like_only"} views.py def post_like_dislike(request, post_id): post = get_object_or_404(Post, pk=post_id) # Like if request.GET.get('submit') == 'like': if request.user in post.dislikes.all(): post.dislikes.remove(request.user) post.likes.add(request.user) return JsonResponse() elif request.user in post.likes.all(): post.likes.remove(request.user) return redirect('mains:posts') else: post.likes.add(request.user) return JsonResponse({'action': 'like_only'}) # Dislike elif request.GET.get('submit') == 'dislike': if request.user in post.likes.all(): post.likes.remove(request.user) post.dislikes.add(request.user) return JsonResponse({'action': 'unlike_and_dislike'}) elif request.user in post.dislikes.all(): post.dislikes.remove(request.user) return JsonResponse({'action': 'undislike'}) else: post.dislikes.add(request.user) return JsonResponse({'action': 'dislike_only'}) else: messages.error(request, 'Something went wrong') return redirect('mains:posts') detail.html <form method="GET" class="likeForm d-inline" action="{% url 'mains:post_like_dislike' data.id %}" data-pk="{{ data.id }}"> <button type="submit" class="btn"><i class="far fa-thumbs-up"></i> <span id="id_likes{{data.id}}"> {% if user in data.likes.all %} {{data.likes.count}}</p> {% else %} {{data.likes.count}}</p> {% endif %} </span><form><button name='submit' type='submit' value="like"> Like </button></form> </button> </form> ERROR When i click on Like button it finely add like but it prints the return Jsonresponse value ( {"action": "like_only"} ). What have i tried Once i tried to redirecting the page into it BUT then failed. Check HereCheck Here Thank You in Advance -
Django: Generate Insert Statements By Passing a Django Object
Is there a way to generate raw MYSQL insert statements for a object and it's related objects. Any package that does this out of box? -
Django AbstractBaseUser MultipleChoiceField
I have created a custom user model with AbstractBaseUser like this: class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) preference = models.CharField(max_length=400) date_joined = models.DateTimeField(default=timezone.now) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name', 'preference'] objects = CustomUserManager() def __str__(self): return self.email For the preference field i don't want a char field, but to create a MultipleChoiceField and when a user sign up to choose what he/she wants from the choices. Is there a simple way to do this? I have a similar form which i used for different purpose: class CategoryForm(forms.Form): def __init__(self, *args, **kwargs): categories = kwargs.pop("Category") super(CategoryForm, self).__init__(*args, **kwargs) self.fields["Category"] = forms.MultipleChoiceField(choices=categories, label='Click this to select categories') -
Using AJAX to run django function from JS
I have a html button. when i press it i want to run a JS function that will call a django function. The website loads but when i press the button nothing happens. can anyone see where I am going wrong? HTML: <input type='button' value='run function' onclick='runScript()'> URLs.py: path('printing_function/', views.printing_function, name='printing_function') views.py: def printing_function(request): print("hello") return HttpResponse() Main.js: function runScript() { $.ajax({ url: 'print_function/', success: function(data) { } }); } -
Django error in test only: django.contrib.auth.models.User.customers.RelatedObjectDoesNotExist: User has no customers
I write test in Django. But for a reason I can't explain, some code that use to work in data migration does not work in tests. I have two models related with a oneToOne relationship: User and Customers. I create Users first and Customers 'based' on Users created just before. Here I use RandomUser API but even if I create User and Customers 'normally' it failed In my tests.py: class CafeTestCase(TestCase): def setUp(self): users1 = RandomUser.generate_users(5) for user in users1: u = User.objects.create( username = user.get_username()+str(random.randrange(100000)), ... date_joined = timezone.now() ) Customers.objects.create( user = u, ... created_at = timezone.now() ) -
How to make migrate Django with Docker
I have docker db and web containers. After command docker-compose up -d --build I have errors with not exists relations in DB. I really don't have tables in DB. I execute following command: $ docker-compose exec web python manage.py migrate And I have following output: Operations to perform: Apply all migrations: admin, auth, autos, bot, contenttypes, sessions, sites Running migrations: Applying contenttypes.0001_initial... OK ... If I execute this command second time, then I get No migrations to apply., but I still don't have tables in DB. Part of my docker-compose.yaml: version: '3.3' x-base: &base restart: unless-stopped build: . working_dir: /code/autotracker env_file: - .env services: web: <<: *base command: gunicorn autotracker.wsgi -b :8001 volumes: - "/static:/static" ports: - "8001:8001" depends_on: - db db: image: postgres restart: unless-stopped volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - .env.db ports: - 5432 volumes: postgres_data: -
Django: ModelForm save() method for multiple objects for a span of dates
I need to make a form to save multiple instances of a Model for a span of dates provided by a user. I have created a ModelForm with a change - exclude date (a model attribute) and added 2 fields: date_from and date_to (for a starting and ending date). I would like the form to save as many records as needed based on the dates span. The code below doesn't work. models.py class Tour(models.Model): company = models.ForeignKey('Company', on_delete=models.PROTECT) employee = models.ForeignKey('Employee', on_delete=models.PROTECT) date = models.DateField() forms.py class TourForm(forms.ModelForm): DATE_INPUT_FORMATS = ['%d-%m-%Y'] date_from = forms.DateField(widget=AdminDateWidget) date_to = forms.DateField(widget=AdminDateWidget) class Meta: model = Tour fields = ['company', 'employee', 'date_from', 'date_to'] def save(self, *args, **kwargs): start_date = self.cleaned_data['date_from'] end_date = self.cleaned_data['date_to'] delta = datetime.timedelta(days=1) count = end_date - start_date while start_date <= end_date: data = { 'company': self.cleaned_data['company'], 'employee': self.cleaned_data['employee'], 'date': start_date, } single_tour = SingleTourForm(data) single_tour.save() start_date += delta class SingleTourForm(forms.ModelForm): DATE_INPUT_FORMATS = ['%d-%m-%Y'] class Meta: model = Tour fields = '__all__' The custom save() method above doesn't work. I get an error 'NoneType' object has no attribute 'save' What should I do to make it work? I am tryign to make it work using Django Admin Panel. -
Django: fetch multiple models
This is my first project with Django, I want to recreate my static HTML/CSS/js site to a dynamic site with an admin panel. However, I have a hard time understanding the views/urls.On my index, I have main news, events, mini news - 3 categories. I can render mainnews, however, I'm not sure what to use as 'return' for the other 2(all 3 are on the belongs to index page) Currently, I have 'index' but doesn't show the events/news. pages>view.py from django.shortcuts import render, redirect, get_object_or_404 from mainnews.models import Mainnews from events.models import Event from mininews.models import Mini # Create your views here. def home_view(request): main_news = Mainnews.objects.order_by('-publish_date').filter(is_published = True)[:1] context = { 'main_news' : main_news } return render(request, 'index.html', context) def event_view(request): events = Event.objects.order_by('-publish_date').filter(is_published = True)[:3] context = { 'events' : events } return render(request, 'index.html', context) def mini_view(request): mini_news = Mini.objects.order_by('-publish_date').filter(is_published = True)[:4] context = { 'mini_news' : mini_news } return render(request, 'index.html', context) main>urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from pages.views import home_view, event_view, mini_view urlpatterns = [ path('admin/', admin.site.urls), path('', home_view, name = 'home'), path('', event_view, name = 'home'), path('', mini_view, name = 'home'), … -
Django - How to filter database using HTML select tag?
I am trying to create an E-Commerce Website. So, I am trying to add filters like Price: Low - to High and vice versa. I know how to filter the price but I don't know how to apply the filter on select value getting changed. Here is HTML Code <div class="d-flex flex-row-reverse" style="margin-right: 20px; margin-bottom: 20px;"> <label> <select class="bg-dark" name="price" id="priceFilter"> <option value="normal">Sort by Price</option> <option value="low">Low-to-High</option> <option value="high">High-to-Low</option> </select> </label> </div> Django Code def index(request): fil = request.GET('price') if fil == "low": products = Product.objects.all().order_by('productDiscountedPrice') elif fil == "high": products = Product.objects.all().order_by('-productDiscountedPrice') else: products = Product.objects.all() context = { 'products': products } return render(request, "Amazon/index.html", context) So, How to sort products when select tag value gets changed? -
How to implement element ordering accross two different models in Django?
I've got these Car and Bike models I can't modify. They may need to be linked to a Ferry model which I can modify. I want to implement ordering of these elements of two different models in the database and I want to avoid using Generic Foreign Keys. So far this is what I've come up with: class Car(models.Model): pass class Bike(models.Model): pass class Ferry(models.Model): pass class Lot(models.Model): position = SmallInteger() car = models.ForeignKey(to=Car, null=True, related_name="ferries") bike = models.ForeignKey(to=Bike, null=True, related_name="ferries") ferry = models.ForeignKey(to=Ferry, null=False, related_name="load") Now my goal is to be able to access directly all the elements of a particular ferry –be they cars or bikes– ordered by position, and all the ferries (in the context of ferry travel bookings there may be several) of a particular car or bike: some_ferry.load.all().order_by("position") some_car.ferries.all() How do I create these relations, including a sort of combination of (car + bike)? -
Django models - Model relations misunderstandings
I want to create a table that only adds some information about another table. Here is what I have: I have 2 tables Exchange and ExchangeConnection: class Exchange(models.Model): slug = models.CharField(max_length=200, primary_key=True, blank=False, null=False) name = models.CharField(max_length=200, blank=False, null=False) class ExchangeConnection(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) exchange = models.OneToOneField(Exchange, on_delete=models.CASCADE) There are multiple exchanges which are defined by me and won't be modified throughout the app usage. It's only useful stored data to make my app works. I see it more like a type of ExchangeConnection. Then, I have ExchangeConnection. This table will be modified throughout the app usages because it represents information that belongs to a user, and it will be able to create some: When the user create an ExchangeConnection, he select which only one Exchange he is using. In my code you can see I'm using OneToOneField which isn't good because It implies an Exchange can be "linked" only once for every ExchangeConnection. I don't want to use ForeignKeyField in Exchange because I don't want ExchangeConnections to be part of an Exchange. I certainly misunderstood the logic of relations so I may bot be clear... -
Context must be a dict rather than list rendering template
I´m making a queryset with django. Now I have a little issue rendering the template. It retuned this error "context must be a dict rather than list". I know that context should be return as a dict, I´m suspecting in the context['cursos'] line. Anyone can confirm my suspect or give me some solution? thanks in advance class ListCursos( TemplateView): model1 = User model2 = Course template_name = 'plantillas/miscursos.html' def get_context_data(self, *args, **kwargs): context = super(ListCursos, self).get_context_data(**kwargs) rels = CourseRelUser.objects.filter(user_id=1) courses_id=[] for rel in rels: courses_id.append(rel.c_id) return courses_id context['cursos'] = Course.objects.filter(id__in=courses_id) return context -
How to add a button that redirects you to html page django admin page
In my case, I was creating a template for a PDF that I wanted to be preview-able directly from the admin page where the template was created, so people could see what the result would be of the object they’d just created. I really just needed a single link with a view that would show a PDF for me, but even something that basic is not immediately obvious in Django admin. I have a TransactionModel registered in the admin page as below : @ admin.register(Transaction) class TransactionAdmin(admin.ModelAdmin): search_fields = ['chp_reference', 'familymember__name'] inlines = [FamilyGroupInline, FamilyMemberInline] def report(self, obj): return mark_safe(json2html.convert(json=obj.report, table_attributes="class=\"results\" style=\"overflow-x:auto;\"")) fieldsets = ( ('Transaction Details', { 'fields': ('chp_reference', 'income_period', 'property_market_rent', 'rent_effective_date', 'number_of_family_group',), }), ('Report', { 'classes': ('collapse',), 'fields': ('report',), }), ) readonly_fields = ['report', 'complete', 'last_rent'] i want the Report object from the fieldsets to be a clickable link that redirect user to a html file, I dont know if that is possible.. and if its, what is the best approach to do so, Thank you! -
Why cannot iterate over Model.objects.all()?
In Django shell I don't have any problems in looping over Airport.objects.all() but in a .py I cannot iterate over my model's QuerySet. Here is my code: from django.forms import ModelForm,DateField,ChoiceField from flights.models import Flight,Airport from django.forms.widgets import SelectDateWidget,TextInput from datetime import datetime # pylint: disable=no-member queries=Airport.objects.all() airports = [tuple(x) for x in queries] I got TypeError: 'Airport' object is not iterable. Why? -
Reverse for 'posts' with keyword arguments '{'id': 106}' not found. 1 pattern(s) tried: ['posts/$']
I am building a BlogApp AND Everything is working fine BUT when i return redirect('mains:posts',id=post_id). It is showing me :- Reverse for 'posts' with keyword arguments '{'id': 106}' not found. 1 pattern(s) tried: ['posts/$'] views.py def post_like_dislike(request, post_id): post = get_object_or_404(Post, pk=post_id) # Like if request.GET.get('submit') == 'like': if request.user in post.dislikes.all(): post.dislikes.remove(request.user) post.likes.add(request.user) return JsonResponse() elif request.user in post.likes.all(): post.likes.remove(request.user) return redirect('mains:posts',id=post_id) else: post.likes.add(request.user) return JsonResponse({'action': 'like_only'}) # Dislike elif request.GET.get('submit') == 'dislike': if request.user in post.likes.all(): post.likes.remove(request.user) post.dislikes.add(request.user) return JsonResponse({'action': 'unlike_and_dislike'}) elif request.user in post.dislikes.all(): post.dislikes.remove(request.user) return JsonResponse({'action': 'undislike'}) else: post.dislikes.add(request.user) return JsonResponse({'action': 'dislike_only'}) else: messages.error(request, 'Something went wrong') return redirect('mains:posts',id=post_id) The Error is is at this Line -----------------^ detail.html <form method="GET" class="likeForm d-inline" action="{% url 'mains:post_like_dislike' data.id %}" data-pk="{{ data.id }}"> <button type="submit" class="btn"><i class="far fa-thumbs-up"></i> <span id="id_likes{{data.id}}"> {% if user in data.likes.all %} {{data.likes.count}}</p> {% else %} {{data.likes.count}}</p> {% endif %} </span><form><button name='submit' type='submit' value="like"> Like </button></form> </button> </form> ERROR When i click on Like button, it is showing Reverse for 'posts' with keyword arguments '{'id': 106}' not found. 1 pattern(s) tried: ['posts/$']. Any help would be Appreciated. Thank You in Advance -
How to run django views.function() on everyday midnight 00:00 using scheduler or schedu
## below created scd.py import schedule import time from .views import * # Create your tests here. def job(): views.attendancetemplate() #a= urllib.request.urlopen(url='http://172.16.1.100:8000/tmp', ) ## this is working but still `enter code here` print("I'm working...") schedule.every().day.at("20:23").do(job) while True: schedule.run_pending() time.sleep(1) #--------------------------------------------------------------------------------------- # THIS IS Views.py #-------------------------------------------------------------------------- from django.contrib.auth.backends import UserModel from django.contrib.auth.models import User from django.contrib.auth.signals import user_logged_in, user_login_failed from django.shortcuts import render , redirect from django.http import HttpResponse from django.contrib import messages from schedule import every from . import views from .models import * from django.contrib.auth import authenticate, get_user, login ,get_user_model, update_session_auth_hash from django.core.exceptions import ObjectDoesNotExist from django.contrib.auth.forms import UserCreationForm from datetime import date from django.contrib.auth.forms import PasswordChangeForm from datetime import timedelta import csv from django.contrib.auth.decorators import permission_required import schedule import time enter image description here ######################################################################################################### ## ****************!IMPORTANT ********************** USER TEMPLATE ######################################################################################################### def attendancetemplate(request): today = datetime.date.today() x=datetime.datetime.now() ldate= Attendance.objects.order_by('id').last() ldate1=ldate.date yesterday = today - timedelta(days = 1) prev = today - timedelta(days = 2) # if ldate1 == yesterday: User1 = get_user_model() users = User1.objects.all() for i in users: uname = i.username iname = i.first_name ausr =Attendance(User_Name = uname,date =today,Name=iname) ausr.save() if i is None: break print("I'm working...") [1]: https://i.stack.imgur.com/ciyLW.png