2

I am new to Django and looking to do something simple.

I have a date database field and I am trying to get Django to display it as a 'date' widget in the HTML forms.

Following is my code:

models.py

from django.db import models                                                                                                                                   

class DateF(models.Model):
    edate = models.DateField()

forms.py

from django.forms import ModelForm                                                                                                                             
from django import forms
from .models import DateF

class DateForm(forms.ModelForm):
    class Meta:                                                                                                                                                
        model = DateF
        fields = ['edate']

views.py

from django.shortcuts import render                                                                                                                            
from .forms import DateForm

def index(request):
    if request.method == 'POST':
        pass
    else:
        form = DateForm()
    return render(request, 'datef/index.html',{'form':form})

Template file

<!DOCTYPE html>
<html>
<head>
<title>Date field test</title>                                                                                                                                 
</head>
<body>
<div style="width: 600px;margin: auto;">
    <h2>Date field</h2>
    <form method="post">
        {% csrf_token %}
        {{ form.as_p }}
   </form>
</div>
</body>
</html>

The above displayed a text input field.

I tried the following in my forms.py based on the following and still could not get it to work.

https://stackoverflow.com/questions/660929/how-do-you-change-the-default-widget-for-all-django-date-fields-in-a-modelform

from django.forms import ModelForm
from django import forms
from .models import DateF
from django.forms import fields as formfields
from django.contrib.admin import widgets

class DateForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(DateForm, self).__init__(*args, **kwargs)
        self.fields['edate'].widget = widgets.AdminDateWidget()   

    class Meta:
        model = DateF
        fields = ['edate']

What am I missing? Do I need to provide any JavaScript?

user2125853
  • 1,265
  • 4
  • 13
  • 23
  • This question shouldn't have been closed. This question quotes the solution from the "duplicate" question, but asks why it doesn't work. I am dealing with the same question. – YCode Apr 09 '22 at 23:11

0 Answers0