Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I order fields in Django ModelForm?

I have an 'order' Model:

class Order(models.Model):      date_time=models.DateTimeField()      # other stuff 

And I'm using Django ModelForm class to render a form, but I want to display date and time widgets separately. I've came up with this:

class Form(forms.ModelForm):      class Meta:         model = Order         exclude = ('date_time',)         date = forms.DateField()         time = forms.TimeField() 

The problem is that I want to put these fields somewhere between 'other stuff'

like image 467
joozek Avatar asked May 23 '10 21:05

joozek


People also ask

How do I sort fields in Django admin?

You can order the fields as you wish using the ModelAdmin. fields option. The order of fields would depend on the order in which you declare them in your models. So alternatively you could order the fields in the way you would want them to show in the admin.

How do you exclude a specific field from a ModelForm?

Set the exclude attribute of the ModelForm 's inner Meta class to a list of fields to be excluded from the form.

What is ModelForm in Django?

Django Model Form It is a class which is used to create an HTML form by using the Model. It is an efficient way to create a form without writing HTML code. Django automatically does it for us to reduce the application development time.

How do I get field value in Django?

To get value from form field with Python Django, we can use the form's cleaned_data property. to use the myform. cleaned_data property to get the form values as a dict.


2 Answers

You can use:

class Meta:     fields = [ ..., 'date', 'time', ... ] 

See the docs: http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#changing-the-order-of-fields

like image 88
Lukasz Korzybski Avatar answered Sep 23 '22 13:09

Lukasz Korzybski


Adding to Lukasz answer, in Django 2.0 the complete admin form registration with field ordering would look like the following:

models.py

class Order(models.Model):     date_time = models.DateTimeField()     # other fields 

admin.py

class OrderForm(forms.ModelForm):     datef = forms.DateField()     timef = forms.TimeField()      class Meta:       model = Order       exclude = ['date_time']       fields = (           'datef',           'timef',           # other fields       )  class OrderAdmin(admin.ModelAdmin):     form = OrderForm  admin.site.register(Order, OrderAdmin) 

Note that date and time fields are defined in ModelForm class and not in Meta class.

like image 24
Alex Volkov Avatar answered Sep 23 '22 13:09

Alex Volkov