Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to render .astro files in django
I tried to create a Django web app since the web pages had heavy js files so it took a long time to load the page. To tackle this problem I tried to implement Astro to create a static webpage. But the problem here is that Django renders .astro files also as HTML.Like shown in this image How do I tell Django to render .astro as an Astro file -
Dynamically iterate over variables if it contains a url using Jinja
I have a collection of uploaded photos in Django admin photos URLs are stored in a Django app namely Listing, inside model.py class Listing(models.Model): photo_1 = models.ImageField(upload_to='photos/%Y/%m/%d/',blank=True) photo_2 = models.ImageField(upload_to='photos/%Y/%m/%d/',blank=True) photo_3 = models.ImageField(upload_to='photos/%Y/%m/%d/',blank=True) photo_4 = models.ImageField(upload_to='photos/%Y/%m/%d/',blank=True) photo_5 = models.ImageField(upload_to='photos/%Y/%m/%d/',blank=True) photo_6 = models.ImageField(upload_to='photos/%Y/%m/%d/',blank=True) my code for views.py looks like def listing(request, listing_id): listing = get_object_or_404(Listing, pk=listing_id) context = { 'listing': listing } return render(request, 'listings/listing.html', context) now, inside my listing.html file I can check if a photo URL is available and then apply the design to show the photo as following {% if listing.photo_1 %} <div class="col-md-2"> <a href="{{ listing.photo_1.url }}" data-lightbox="home-images"> <img src="{{ listing.photo_1.url }}" alt="" class="img-fluid"> </a> </div> {% endif %} I can do it for all six photos but I want to do it dynamically like {% for i in range (1,7) %} {% if listing.photo_{{i}} %} <div class="col-md-2"> <a href="{{ listing.photo_{{i}}.url }}" data-lightbox="home-images"> <img src="{{ listing.photo_{{i}}.url }}" alt="" class="img-fluid"> </a> </div> {% endif %} {% endfor %} is there any way to do it? I tried to pass photos URLs inside the context dictionary as a list like def listing(request, listing_id): listing = get_object_or_404(Listing, pk=listing_id) context = { 'listing': listing 'photos': [listing.photo_1,listing.photo_2,listing.photo_3,listing.photo_4,listing.photo_5,listing.photo_6] } return render(request, 'listings/listing.html', context) … -
How do I use Django's CheckConstraint to restrict a variable at the database level?
I'm trying to write an application that receives incoming tickets for a small IT department. Currently these tickets come in through a webhook so I want to restrict what comes in at the database level. I want to restrict the status variable of the ticket to the choices described in the ticketStatus model but the database is still accepting values outside these choices. I've experimented with using CheckConstraint but can't quite get it to work. My code is as follows: class ticketStatus(models.TextChoices): Active = "Active" Acknowledged = "Acknowledged" Resolved = "Resolved" Unresolved = "Unresolved" class Ticket(models.Model): dateTimeRecieved = models.DateTimeField(default=timezone.now) deviceId = models.ForeignKey(Device, related_name="Device", on_delete=models.DO_NOTHING) issue = models.CharField(max_length=100) status = models.CharField(max_length=20, default="Active") def __str__(self): return f"Device {self.deviceId}: {self.issue}" class Meta: constraints = [ models.CheckConstraint( models.Q(status__in=ticketStatus.values) ), ] At the moment, I'm getting this error when I attempt the migration: TypeError: __init__() takes 1 positional argument but 2 were given I believe this is associated with models.Q(status__in=ticketStatus.values) I'm currently using Django version 3.2.4 -
Return pk of form after submission
I need to return the PK of a form after it is submitted so I can use it in a second form. Everything I find online about returning the PK is for a http redirect not storing it in a variable and working with it in the view view def createPostView(request): currentUser = request.user postForm = PostForm() if request.method == 'POST': postForm = PostForm(request.POST, request.FILES) if postForm.is_valid(): PostFormID = postForm.save(commit=False) PostFormID.author = request.user PostFormID.save() return #need to get pk from this form for f in request.FILES.getlist('images'): test = PostImagesForm(request.POST, request.FILES) if test.is_valid(): instance = test.save(commit=False) instance.post = #need to use pk here instance.images = f instance.save() return HttpResponseRedirect("/") return render(request, 'blog/post_form.html', {'postForm': postForm, 'PostImagesForm':PostImagesForm}) -
Cant display values in Django templates
I'm new to Django, I am trying to display a single book in a template(show.html) like <h1 class="text-center text-4xl py-5">{{book.title}}</h1> <img src="{{ book.thumbnailUrl }}" alt="" class="w-56"> <p>{{book.shortDescription}}</p> <p>{{book.longDescription}}</p> The view rendering the template is (trying to render a single book from JSON file by id) def show(request, id): with open('bookstore/books.json') as file: book_dict = json.load(file)['books'] book = [book for book in book_dict if book['id'] == id] context = {'book': book} return render(request, 'books/show.html', context) When debugging by printing {{ book }} in show.html it results in a list with a dictionary of a book [{'id': 1, 'title': 'Unlocking Android', 'isbn': '1933988673', 'pageCount': 416, 'publishedDate': {'$date': '2009-04-01T00:00:00.000-0700'},...}] Hence I think that's the problem when I try to access the title using dict syntax like({{ book. title}} ) But I can't seem to find a workaround. -
Django saves time data in UTC despite using localtime
In my settings file, I have : LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Kolkata' USE_I18N = True USE_L10N = True USE_TZ = True in my views: import datetime def some_function: print(datetime.datetime.now()) << prints my local time However, when using the same datetime.datetime.now() to store the current localtime into a DateTimeField, it gets converted in UTC. I understand that its a good things that it all gets converted into UTC when being stored into Database. Objective being, it will be easier for us to convert UTC to any localtime when we are using these stored values and rendering to the user. This last step, of converting UTC time to localtime, which I assume that django should do by default, is where I'm stuck at. the datetime values are still being rendered as UTC instead of my localtime despite using USE_TZ = True in my settings. -
How can I let my users send email from my django app?
I have a django app and users can create a profile and upload their contacts. Is there a way for me to allow them to send email using their email account but through the app? The use case would be that a user would like to send 50 emails to its contacts that are sent through his own email thought. As i write this, I feel this is not possible - lol -
How to query a Django queryset through a foreign key on another model?
I have the following models in my project: class Case(models.Model): ... class File(models.Model): class StatusType(models.TextChoices): ACTIVE = "ACTIVE", _("ACTIVE") DELETED = "DELETED", _("DELETED") case = models.ForeignKey(Case, on_delete=models.CASCADE, null=True) user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) status = models.CharField( max_length=255, choices=StatusType.choices, default=StatusType.ACTIVE, ) Basically, in one of my views, I want to a get a list of all the cases where the following conditions are met through the File model: user = request.user status = "ACTIVE" How can I do this in a simple way? I can query for all the files first and then loop through them and add the cases to a list. Is that the best way to go about this problem? Thanks in advance for any help. -
AttributeError: 'User_Profile' object has no attribute '__name__'
Hello I hope everyone is having a good day, my goal is to get my forms.py to send the email form content to a different model into my Django database, from the default User model in Django to my custom-made User_Profile model. I believe if I can fix the error above that, my goal will be accomplished. In my forms.py file, I am importing a class from the model.py then using the function again in the forms.py, which is what is causing the error. I did my research on __ name__ with classes, and from what I understood, it has to do with using the same class two different times and it doesn't know which one to run or something. If someone could explain __name __ with classes better and help me fix the error, I would much much appreciate that. Here is my models.py class User_Profile(models.Model): user = models.OneToOneField(User, null = True, blank = True, on_delete = models.CASCADE) name = models.CharField(max_length = 200, null = True) phone = models.CharField(max_length = 200, null = True) email = models.CharField(max_length = 200, null = True) profile_image = models.ImageField(null = True, blank = True) data_created = models.DateTimeField(auto_now_add = True, null = True) def … -
How can i update the field of a model from another model field in django?
I have two models. DepartmentGoal with a field 'scores' and Task also with a field 'scores' and a foreign departmentgoal. What I want is; If I allocate scores to DepartmentGoal, scores allocated to Task should subtract from scores of DepartmentGoal which means Any number of instances of scores of Task when summed up should be equal to score of a single instance of DepartmentGoal. I just need a clue on how to implement this. This are the models class DepartmentGoal(models.Model): name = models.TextField(max_length=150, null=True) score = models.IntegerField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True, null=True) updated_at = models.DateTimeField(auto_now=True, null=True) def __str__(self): return self.name class Task(models.Model): name = models.CharField(max_length=300, null=True) departmentgoal = models.ForeignKey(DepartmentGoal, on_delete=models.CASCADE, related_name='departgoal', null=True, blank=True) score = models.IntegerField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True, null=True) updated_at = models.DateTimeField(auto_now=True, null=True) def __str__(self): return self.name Here the the forms class DepartmentGoalForm(ModelForm): class Meta: model = DepartmentGoal fields = ( ('name'), ('score'), ) class TaskForm(ModelForm): class Meta: model = Task fields = [ 'departmentgoal', 'name', 'score', ] -
Python Django: How to pass in variable with 'url' call inside of template
I want to be able to pass in a variable for this url function defined in my urls.py: path("edit/<str:title>", views.edit, name="edit"), From my html template, I did this: <a href="{% url 'encyclopedia:edit/{{ entry }}' %}">Edit Entry</a> The goal of this is so the user can click this hyperlink to edit some text within in a textarea box. For that I wanted to pass in the specific name of the page, e.g. HTML. That is what the "entry" variable is used for. However, because of this little bit of code 'encyclopedia:edit/{{ entry }}' I get an error: Here is the error: Reverse for 'edit/{{ entry }}' not found. 'edit/{{ entry }}' is not a valid view function or pattern name. I am fairly new to Django, but I know that I am using Django syntax incorrectly in this case. Usually I would be able to do this with a simple <a href="edit/{{ entry }}">Edit Entry</a> But will this pass in "entry" as a variable? -
Django - myfunc() got an unexpected keyword argument 'paramName'
I'm a front-end developer. trying to create a view in django for our app. inside my app I have created a file utils.py where I have a function which expects a record id to some stuff. In my views.py after importing when I call it I'm getting an error: myfunc() got an unexpected keyword argument 'paramName' calling the function like so: funcFromUtilsPy(myObj['id']) I have tried printing paramName inside the function and it's receiving the id. not what this error means and what's causing it. any suggestions ? -
Registration not working in django on Heroku
I have this weird situation where my term project has been deployed at heroku. It works fine except the database part. After searching it up, most of the suggestions were to make migrations. But when I try to migrate it gives me the following error: OSError: SavedModel file does not exist at: ./multiclass_verification_model/{saved_model.pbtxt|saved_model.pb} The code that loads the model is: model = tf.keras.models.load_model("./multiclass_verification_model") I have also tried: model = tf.keras.models.load_model("/multiclass_verification_model") and model = tf.keras.models.load_model("/app/multiclass_verification_model") it is not working. I am short on time as my project evaluation is drawing near. Any help would be really appreciated. Thank you. -
Django 'AnonymousUser' object is not iterable after added delete function in my views
I am getting this error if user isn't login and try to go admin page 'AnonymousUser' object is not iterable. I am getting this error after added delete function in my views: views.py def DeleteNotificaton(request,noti_id): user= request.user author = Blog.objects.filter(author=user) if user.is_authenticated and not author: Notifications.objects.filter(id=noti_id,receiver=user).delete() Notifications.objects.filter(id=noti_id,sender=user).delete() messages.add_message(request, messages.INFO, 'Notification deleted sucessfully.') return redirect('notifications:notify') elif user.is_authenticated and author: Notifications.objects.filter(id=noti_id,receiver=user).delete() messages.add_message(request, messages.INFO, 'Notification deleted sucessfully.') return redirect('notifications:notify_author') I also tried this: def DeleteNotificaton(request,noti_id): user= request.user if user.is_authenticated: author = Blog.objects.filter(author=user) if user.is_authenticated and not author: Notifications.objects.filter(id=noti_id,receiver=user).delete() Notifications.objects.filter(id=noti_id,sender=user).delete() messages.add_message(request, messages.INFO, 'Notification deleted sucessfully.') return redirect('notifications:notify') elif user.is_authenticated and author: Notifications.objects.filter(id=noti_id,receiver=user).delete() messages.add_message(request, messages.INFO, 'Notification deleted sucessfully.') return redirect('notifications:notify_author') getting this error The view notifications.views.DeleteNotificaton didn't return an HttpResponse object. It returned None instead. -
Weighted average from queryset - Django
How get the weighted average from queryset as quickly as possible. Is it possible without the use of loops. Below is an example. My models.py: class Product(models.Model): price = models.DecimalField(max_digits=15, decimal_places=2) weighted = models.IntegerField() day = models.IntegrField() In my database, I have the following values for day 1: Object ID I: Price=100, weighted=12, day=1 Object ID II: Price=50, weighted=1, day=1 Object ID III: Price=75, weighted=3, day=1 how to calculate the weighted average for day one? day_1_average_weighted = Product.objects.filter(day=1) ???how to get a weighted average - 71.88??? -
Django: Delete ForeignKey instance but keep some of its data on record (for Ecom)
Say you have 2 ecom related models: User and Order. On the Order, you want to keep the User's data because there's a transaction that occurred, and you'd most likely like to keep the customers info, however, you'd also like to allow the customer to delete their account should they choose. For example, the way I see it is something like: from django.contrib.auth import get_user_model from django.db import models class Order(models.Model): customer_email = models.EmailField() customer_first_name = models.CharField(max_length=50) customer_last_name = models.CharField(max_length=50) customer = models.ForeignKey(get_user_model(), on_delete=SET_NULL) def clean(self): if not self.customer_first_name: self.customer_first_name = self.customer.first_name if not self.customer_last_name: self.customer_last_name = self.customer.last_name if not self.customer_email: self.customer_email = self.customer.email def save(self, *args, **kwargs): self.full_clean() return super().save(*args, **kwargs) But that seems like a bunch of duplication. Is there a way to go about building that without duplication, or do you just have to live with writing the same fields from the User model but with different names? -
Trying to use a Model method in View Django
So I'm working on this project (an Inventory app). I have this model method I am trying to use in my View. I'm trying to call it in my view. But I'm always getting an error: 'QuerySet' object has no attribute 'get_quantities_sold' Here is my model: generate_ref_no = str(uuid.uuid1()) class Transaction(models.Model): business = models.ForeignKey(Business_Account, on_delete=models.CASCADE) customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True) amount = models.FloatField() productSold = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) quanties_of_product_sold = models.IntegerField() transaction_date = models.DateTimeField(auto_now_add=True) payment_method = models.CharField(choices=PAYMENT_METHOD, max_length=50) reference_num = models.CharField(max_length=50, editable=False, default=generate_ref_no) def __str__(self): return f'{self.customer} ' def get_quantities_sold(self,quantities_sold): return print(quantities_sold) My view: class TransactionView(generics.GenericAPIView): def post(self,request, business=None): serializer = TransactionSerializer(data=request.data) if serializer.is_valid(): serializer.save() getTransaction = Transaction.objects.filter(reference_num=serializer.data['reference_num']) getTransaction_serializer = TransactionSerializer(getTransaction, many=True) getTransaction.get_quantities_sold(serializer.data['quanties_of_product_sold ']) return Response(data=serializer.data, status=status.HTTP_201_CREATED) else: return Response(data=serializer.errors, status=status.HTTP_404_NOT_FOUND) I'm trying to call the 'get_quantities_sold' method from the Transaction model in my transaction view but I'm an error: QuerySet' object has no attribute 'get_quantities_sold' -
Django admin css doesn't work when using aws s3 buckets
I am using s3 buckets on AWS to store my statics files and media files which works well for my site but when doing this the css on my the django admin page doesn't work. Here is my settings: STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) AWS_ACCESS_KEY_ID = '*' AWS_SECRET_ACCESS_KEY = '*' AWS_STORAGE_BUCKET_NAME = 'name' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_S3_REGION_NAME = 'eu-west-2' -
Django Apache 2 ModuleNotFoundError: No module named 'django'
I am trying to deploy my django application on apache2, I am on an AWS ec2 ubuntu instance. Originally I got an Fatal Python error: Py_Initialize: Unable to get the locale encoding, so I switched my python from 2.7 to 3.6 by removing my env and starting a new virtual env on 3.6, I also purged python 2.7 and 3.7 from my instance. After that I got a no module named 'Django error' in my apache. Any help is appreciated been stuck on a while with this :). <VirtualHost *:80> ServerAdmin webmaster@example.com DocumentRoot /home/ubuntu/pydjangoenv/myproj ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/ubuntu/pydjangoenv/myproj/static <Directory /home/ubuntu/pydjangoenv/myproj/static> Require all granted </Directory> <Directory /home/ubuntu/pydjangoenv/myproj/myproj> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess delta_new python-path=/home/ubuntu/pydjangoenv/myproj python-home=/home/ubuntu/pydjangoenv/venv2 WSGIScriptAlias / /home/ubuntu/pydjangoenv/myproj/myproj/wsgi.py </VirtualHost> Also when I run pip3 install django my django is in Requirement already satisfied: django in /home/ubuntu/pydjangoenv/venv2/lib/python3.6/site-packages (3.2.5) -
How do I add a new field using conditional expression?
I'm currently using Django and its in-built database. Assuming in the models.py file, I have a class called User: class User(models.Model): RACE = [ ('0', 'Black'), ('1', 'White'), ('2', 'Asian'), ('3', 'Hispanic'), ('4', 'Others'), ] ASIAN = [ ('0', 'Chinese'), ('1', 'India'), ('2', 'Filipino'), ('3', 'Japanese'), ('4', 'Korean'), ('5', 'Vietnamese'), ('6', 'Others'), ] HISPANIC = [ ('0', 'Mexican'), ('1', 'Puerto_Rican'), ('2', 'Others'), ] race = models.CharField(max_length = 1, choices = RACE, null=True) sub_race = models.CharField(max_length = 1, choices = ASIAN, null=True) if race == 'Asian' else (models.CharField(max_length = 1, choices = HISPANIC, null=True) if race == 'Hispanic' else '0') I was hoping to create a field called sub_race, where its value depends on race. Nonetheless, the above method does not work. Is there a way to fix it ? -
Manipulating the data of a Model field from another model Django
I need some assistance with this if possible. So in the code below, what I tried to do is make a function that checks if there's any order in the database, if there is then I increment the value variable by 1 (and this has to happen each time a new order is made and the variable will keep getting updated, not quite sure if that's alright like that). Then I made a function to set a name for a field in my Counter model and what I want to do is go to the Order model and set that field as the value of code attribute there. To be more specific: class Order(models.Model): code = models.CharField(max_length=10, unique=True) code_year = models.IntegerField class Counter(models.Model): def count(self): value = 0 code_year = Order.objects.get['code_year'] if Order.objects.filter(code_year=code_year).exists(): value += 1 return value @property def names(self): return "P+ %s + %s" % (self.value, Order.code_year) name = models.CharField(max_length=10) value = models.IntegerField(validators=[count]) So basically, I concatinated the fields that I wanted and set that to the name field in Counter. Now I need the value of this name to bet set as the value of code on the Order model. Also quick question, will the value get … -
Django how to disappeared bootstrap alert box messages after few seconds
Before posting this question I found few solutions on stackoverflow and tried but non of them didn't work. I want the message will be disappeared after 2 or three seconds. here is my code: {% if messages %} <ul class="messages"> {% for message in messages %} <div class="alert alert-danger" role="alert"> <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> {% endfor %} </div> </ul> {% endif %} it look like this: here given below few JavaScript code which I tried for disappeared the alert box after few seconds but none of them didn't work: code1: <script text="javascript"> setTimeout(fade_out, 3000); function fade_out() { $(".messages").fadeOut().empty(); } </script> code2 <script> $(document).ready(function() { // messages timeout for 10 sec setTimeout(function() { $('.message').fadeOut('slow'); }, 10000); // <-- time in milliseconds, 1000 = 1 sec // delete message $('.alert').live('click',function(){ $('.alert').parent().attr('style', 'display:none;'); }) }); </script> code3 <script> setTimeout(function() { $('.messages').fadeOut('fast'); }, 30000); // <-- time in milliseconds </script> -
Using Ajax to update model data after javascript alert button click - Django
I have a javascript alert (It uses swal to style it, but it functions like a regular alert). I want to run SomeModel.objects.filter(id=id).delete() after the ok button is clicked. I did research online, and I came across many articles talking about using Ajax, but I can't really figure it out. Can someone please help me? My code is down bellow. swal({ title: "Accept Donation", text: "Are you sure you would like to accept the donation titled {{donation.title}}, which was posted on {{donation.date}} by {{donation.user}}?", icon: "info", buttons: true, }) .then((ok) => { if (ok) { swal("Donation successfully accepted, please contact {{donation.user}} at {{donation.phonenumber}}, for instructions as to when and where you should pick up the donation", { icon: "success", }); } }); } Views.py: def acceptdonation(request): donations = Donation.objects.all() context = {} return render(request, 'acceptdonation.html', context) -
why html element created by javascript being appended multiple times in html page?
I have a Django project and I need to add a new email to the HTML page, however each time I click on the button, the content will be appended again, I want the information to be appended once using the function show_email(email, mailbox) , and for the buttons to be disabled if the user is on the mailbox section and enabled again when the user clicks on another button. ps. this is a one-page project. JS : document.addEventListener('DOMContentLoaded', function() { // Use buttons to toggle between views document.querySelector('#inbox').addEventListener('click', () => load_mailbox('inbox')); document.querySelector('#sent').addEventListener('click', () => load_mailbox('sent')); document.querySelector('#archive').addEventListener('click', () => load_mailbox('archive')); document.querySelector('#compose').addEventListener('click', compose_email); document.querySelector('form').onsubmit = send_email; // By default, load the inbox load_mailbox('inbox'); }); function send_email() { const recipients = document.querySelector('#compose-recipients').value; const subject = document.querySelector('#compose-subject').value; const body = document.querySelector('#compose-body').value; fetch('/emails', { method: 'POST', body: JSON.stringify({ recipients: recipients, subject: subject, body: body }) }) .then(response => response.json()) .then(result => { // Print result console.log(result); }); localStorage.clear(); load_mailbox('sent'); return false; } function show_email(email, mailbox) { let emailContainer = document.createElement('div'); emailContainer.id = "email" emailContainer.className = "row"; let recipient = document.createElement('div'); recipient.id = "email-recipient" recipient.className = " " if (mailbox === "inbox"){ recipient.innerHTML = email.sender; } else { recipient.innerHTML = email.recipients[0]; } emailContainer.append(recipient); let subject … -
Django HTML Send POST data to url as PK value when submitting
I have a form that's just a date field and submit button Forms.py from django import forms from datetime import date class DateInput(forms.DateInput): input_type = 'date' class HomeForm(forms.Form): EnterDate = forms.DateField(widget=DateInput, initial=date.today()) Because of a user request, I just want to send the data to the url like this home/2021-07-01 so I tried to do this for my html form, just stick the form.EnterDate.value in the form Action part, but it only works on the 2nd try. <form method="POST" class="form-inline my-2 my-lg-0" action="{% url 'mint-post' form.EnterDate.value %}"> {% csrf_token %} <label for="{{form.EnterDate.id_for_label}}">Enter Date</label> {{form.EnterDate}} <button class="btn btn-primary my-2 my-sm-0" type="submit">Submit Date</button> #Inital loading the form def mintHome(request): form = HomeForm() context = { 'form': form } return render(request, 'mintyHome.html', context) #after Post def mintHomePost(request, pk): if request.method =='POST': form = HomeForm(request.POST) if form.is_valid(): datePost = form.cleaned_data['EnterDate'] stringDate = datePost.strftime("%Y%m%d") context = { 'form': form } return render(request, 'mintyHome.html', context) I made an example here: https://alisayt.pythonanywhere.com/minty/home/2021-07-07 It sends the form.EnterDate.value only in the 2nd submit, but not the first one.