DateField doesn't work in forms.py - django

I'm trying to create a date input field, but it shows as a simple input text, i'm using django 1.10, thanks in advance.
from django import forms
import datetime
from .models import Student
class StudentForm(forms.ModelForm):
class Meta:
model = Student
fields = ["name","date"]
widgets = {
'date': forms.DateInput(format="%d/%m/%Y")}

Related

Django CheckboxSelectMultiple not displaying in ModelForm

I'm trying to use CheckboxSelectMultiple in a form, instead of the SelectMultiple default. I tried two different ways to make it display as checkboxes, but they both display the default SelectMultiple on my local webpage. Everything else renders correctly ( {{ form.as_table }} ). Would someone point me in the right direction? Thanks,
Django version 3.0.2
Python 3.6.9
models.py
class MyModel(models.Model):
m2m = models.ManyToManyField('OtherModel', blank=True)
[...]
forms.py
from django.forms import ModelForm
from myapp.models import MyModel
class MyModelModelForm(ModelForm):
[...]
# I tried this...
m2m = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple)
class Meta:
model = MyModel
fields = '__all__'
# or this...
widgets = {
'm2m': forms.CheckboxSelectMultiple,
}
views.py
from django.views.generic.edit import CreateView
from myapp.models import MyModel
class MyModelCreate(CreateView):
model = MyModel
fields = '__all__'
template_name = 'MyApp/mymodel_form.html'
You did not use the form you constructed. You simply constructed a ModelForm, and then let the CreateView create another ModelForm since you did not specify a form_class [Django-doc].
You can thus update the CreateView, and work with:
from django.views.generic.edit import CreateView
from myapp.models import MyModel
from myapp.forms import MyModelModelForm
class MyModelCreate(CreateView):
model = MyModel
form_class = MyModelModelForm
template_name = 'MyApp/mymodel_form.html'

Django DateInput() widget not working in ModelForm

I'm making a user login form with a CustomUser model derived from AbstractUser, with one extra field: date_of_birth. I use CreateView to generate the form. All fields show up, the password field uses the password widget as expected (showing dots instead of characters), but the date field does not (plain character field with no formatting or calendar). What am I overlooking?
models.py:
from django.urls import reverse
from django.contrib.auth.models import AbstractUser
# Create your models here.
class CustomUser(AbstractUser):
date_of_birth = models.DateField(verbose_name="Date of Birth", blank=True, null=True)
def get_absolute_url(self):
return reverse('index')
def __str__(self):
return self.username
forms.py:
from .models import CustomUser
class CustomUserForm(forms.ModelForm):
class Meta:
model = CustomUser
fields = ["username", "password", "first_name", "last_name", "email", "date_of_birth"]
widgets = {
"password": forms.PasswordInput(),
"date_of_birth": forms.DateInput()
}
views.py:
from django.views.generic.edit import CreateView
from .models import CustomUser
from .forms import CustomUserForm
# Create your views here.
def index(request):
return HttpResponse("Hello, world")
class CustomUserCreate(CreateView):
model = CustomUser
form_class = CustomUserForm
If you come here in 2020 and beyond, just overide the default type=text undelying input by using 'type':'date'
So something like the below would work. Tested on Mozilla Dev Edition 73.+
'date_of_birth': forms.DateInput(attrs={'class':'form-control', 'type':'date'}),
Django has no built-in fancy datepicker. DateField uses the DateInput widget which is just a text input.
Thanks voodoo-burger for pointing me in the right direction. I found a video with a very simple solution to use the HTML5 datepicker: https://www.youtube.com/watch?v=I2-JYxnSiB0.
It only requires to add the following to forms.py:
class DateInput(forms.DateInput):
input_type = 'date'
and then use this as the widget (so replace forms.DateInput() with DateInput()).

Django - rendering date field in template

I am working on a form which is used to stores student data. when I tried to render the form it produces an text input instead of data.
How do i render date input using django
forms.py
class StudentRegister(forms.Form):
firstname = forms.CharField(max_length= 50)
lastname = forms.CharField(max_length = 50, required=False)
mail = forms.EmailField(required=False)
dob = forms.DateField()
html
{{form.dob}}
{{form.dob.error}}
By default Django will display TextInput field, You can override your form to display DateField..
class DateInput(forms.DateInput):
input_type = 'date'
class StudentRegisterForm(ModelForm):
class Meta:
model = StudentRegister
fields = '__all__'
widgets = {
'dob': DateInput()
}
Use SelectDateWidget:
from django.forms import SelectDateWidget
# from django.forms.extras.widgets Django < 1.9
from django.utils import timezone
def past_years(ago):
this_year = timezone.now().year
return list(range(this_year, this_year - ago - 1))
class StudentRegisterForm(forms.Form):
...
dob = DateField(widget=SelectDateWidget(years=past_years(100))
Just a small correction on the previous reply by Vladimir Danilov
from django.forms import SelectDateWidget
# from django.forms.extras.widgets Django < 1.9
from django.utils import timezone
def past_years(ago):
this_year = timezone.now().year
return list(range(this_year-ago-1, this_year)) #<------- Parameters should be inverted here
class StudentRegisterForm(forms.Form):
dob = DateField(widget=SelectDateWidget(years=past_years(100))

Removing fields from django-rest-framework view

is there any way to show only a list of fields or excluding some of them when using django-rest-framework?
Here's my app/views.py:
from rest_framework.generics import ListAPIView
from .models import PhpbbUsers
class UsersReadView(ListAPIView):
model = PhpbbUsers
Obiously there are some user information that I don't want to show to everyone. How could I do?
Solution code
from rest_framework import generics, serializers
from .models import PhpbbUsers
class UsersSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = PhpbbUsers
fields = ('user_id', 'username', 'user_avatar')
class UsersReadView(generics.ListAPIView):
model = PhpbbUsers
serializer_class = UsersSerializer
Set the serializer_class attribute on the view.
See the quickstart for a good example: http://django-rest-framework.org/tutorial/quickstart.html

Django URLField and HTML5?

Is it possible to make django's (v1.2) URLField output an HTML5 input tag where type="url"?
------------- SOLUTION -------------
from django.forms import ModelForm
from django.forms import widgets
from django.forms import fields
from models import MyObj
class URLInput(widgets.Input):
input_type = 'url'
class MyObjForm(ModelForm):
url = fields.URLField(widget=URLInput())
class Meta:
model = MyObj
You have to create a custom widget for that.
class URLInput(forms.TextInput):
input_type = 'url'
Then you can pass this widget to URLField constructor:
class MyForm(forms.Form):
url = forms.URLField(widget=URLInput())