IordanouGiannis
IordanouGiannis

Reputation: 4357

Getting None from form in Django

In one of my django I have a form that creates a new product in the database:

views.py

class ProductCreateView(LoginRequiredMixin, CreateView):
    template_name = "products/my-products.html"
    model = Product
    form_class = AddNewProductForm

    def form_valid(self, form):
        obj = form.save(commit=False)
        obj.user = self.request.user
        obj.save()
        return HttpResponseRedirect("/my-products/")

forms.py

AVAILABLE_YEAR_CHOICES = list(range(1960, 2051))

class AddNewProductForm(forms.ModelForm):

    class Meta:
        model = Product
        fields = ["date", "time", "title", "desrciption"]
        widgets = {'date': forms.SelectDateWidget(years=AVAILABLE_YEAR_CHOICES)}

Using the above, everything works perfectly.

I wanted to add the current date and time to the date and time widgets, so I tried the following:

forms.py

class AddNewProductForm(forms.ModelForm):
    date = forms.DateField(label='date', initial=datetime.date.today(),
                           widget=forms.SelectDateWidget(years=AVAILABLE_YEAR_CHOICES))
    time = forms.TimeField(label="time", initial=datetime.datetime.now().strftime("%H:%M"))
    class Meta:
        model = Product
        fields = ["title", "desrciption"]

When I use this, I get an error that the date field is None.

I am not sure why this is really happening. Using just the fields in Meta works, but doing something custom gives None.

Upvotes: 0

Views: 829

Answers (2)

Vadym
Vadym

Reputation: 1555

You can use get_initial_for_field method for it

AVAILABLE_YEAR_CHOICES = list(range(1960, 2051))

class AddNewProductForm(forms.ModelForm):
    class Meta:
        model = Product
        fields = ["date", "time", "title", "desrciption"]
        widgets = {'date': forms.SelectDateWidget(years=AVAILABLE_YEAR_CHOICES)}

    def get_initial_for_field(self, field, field_name):
        if field_name == 'date':
            return datetime.date.today()
        if field_name == 'time':
            return datetime.datetime.now().time()
        return super().get_initial_for_field(field, field_name)

Also instead of datetime.datetime.now().strftime("%H:%M") do next datetime.datetime.now().time()

Upvotes: 0

msc
msc

Reputation: 3800

You also need to specify the fields in the second example:

class AddNewProductForm(forms.ModelForm):
    date = forms.DateField(label='date', initial=datetime.date.today(),
                           widget=forms.SelectDateWidget(years=AVAILABLE_YEAR_CHOICES))
    time = forms.TimeField(label="time", initial=datetime.datetime.now().strftime("%H:%M"))
    class Meta:
        model = Product
        fields = ["title", "description", "date", "time"]

Upvotes: 1

Related Questions