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'
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.
Set the exclude attribute of the ModelForm 's inner Meta class to a list of fields to be excluded from the form.
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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With