I'm working on a project that has a Chapter, with each Chapter having a title, content, and order. I'd like to keep the field 'order' named as is, but have the field displayed in a CreateView as something else, like 'Chapter number'. The best information I've found recommends updating the "labels" attribute in the Meta class, but this isn't working for me.
This is what I'm using now, which doesn't work:
class ChapterCreate(CreateView):
model = models.Chapter
fields = [
'title',
'content',
'order',
]
class Meta:
labels = {
'order': _('Chapter number'),
}
I've also tried using the 'label's attribute outside of Meta, but that didn't work either. Should I be using a ModelForm instead, or is there a correct way to do this?
The simplest solution in this case would be to set the verbose_name for your model field
class Chapter(models.Model):
order = models.IntegerField(verbose_name= _('Chapter number'))
Note I have use IntegerField in this example, please use whatever type is required.
Even if it is an old subject, I think a way to do this now with Django 3.1 would be:
in views.py
class ChapterCreate(CreateView):
model = models.Chapter
form_class = ChapterForm
and in forms.py, define ChapterForm
class ChapterForm(ModelForm):
class Meta:
model = models.Chapter
fields = ('title', 'content','order')
labels = {
'order': _('Chapter number'),
}
If you want different values for the verbose_name of the model field and the user-facing label of the form field, the quickest way might be to override the get_form(…) method of CreateView:
class ChapterCreate(CreateView):
(...)
def get_form(self, form_class=None):
form = super().get_form(form_class)
form.fields['order'].label = _('Chapter number')
return form
Related
I am trying to understand the process of generating generic form views in django. I have a generic view class with just
class BookUpdate(UpdateView):
model = Book
fields = [ 'name',
'pages',
'categorys'
]
which automatically generates a working html form from my model data. But now, I want to modify the field that is shown for categorys, is there any way to do this, or do I have to create a complete working BookForm class and custom BookUpdate class? Here its just 3 fields, but in my real case there are maybe 15 fields that I would need to code by myself, just because of a tiny change in the category field.
Cant I just overwrite the single field, using any class method?
You can either specify fields or form_class in your generic class-based view. With fields, Django will use a modelform_factory to generate the form. There's not much you can customise then.
You should create a BookForm class so that you can customise the fields. In your BookUpdate view, you only need to remove fields and add form_class = BookForm. Here I'm customising the widget for categorys and overriding the form field for pages:
def BookUpdate(UpdateView):
model = Book
form_class = BookForm
def BookForm(ModelForm):
pages = MyCustomPagesField()
class Meta:
model = Book
fields = '__all__'
widgets = {'categorys': MyCustomWidget()}
Note that you don't have to specify all fields, you can use "__all__" to have all fields or you can set exclude = [<list fields to exclude>] to just exclude a couple.
You don't have to code the fields yourself. But there is a small amount of work to do, as there isn't a method to override.
What you need to do is define a custom form. Since that will be a ModelForm, it will use the same logic to automatically create its fields based on the model. You can then override the definition of one of them.
class BookForm(forms.ModelForm):
categorys = forms.ModelMultipleChoiceField(custom_attributes_here...)
class Meta:
model = Book
fields = ["name", "pages", "categorys"]
And now tell your view to use that form:
class BookUpdate(UpdateView):
form_class = BookForm
I am trying to use TreeBeard's built in Form's with django forms (not admin). I specifically wanted to replace the rendering of a Select ForeignKey field with TreeBeard forms format. I thought I could do this by declaring the field in my ModelForm, but I've had no success. I'm new to django so my understanding is limited.
These are my initial classes in my forms.py
MyCategories = movenodeform_factory(Category)
class CreatePost(ModelForm):
class Meta:
model = Post
fields = ['title', 'category', 'region', 'content', ]
I tried implementing it by declaring the category field in the beginning but this clearly isn't the way to do it. The declaration does return an html formatted category list, but I can't replace the Post category (which is a ForeignKey)with it.
class CreatePost(ModelForm):
category = movenodeform_factory(Category)
class Meta:
model = Post
fields = ['title', 'category', 'region', 'content', ]
The reason I want to use TreeBeard forms is because of the way it nests the fields according to the category hierarchy.
SOLVED:
This ended up being much simpler than I realized.
class CreatePost(ModelForm):
CHOICES = MoveNodeForm.mk_dropdown_tree(Category)
category = ChoiceField(choices=CHOICES)
class Meta:
model = Post
fields = ['title', 'category', 'region', 'content', ]
The solution was right in front of me. I just needed to create a list using mk_dropdown_tree and use it in a ChoiceField. I hope this might help someone someday.
class CreatePost(ModelForm):
CHOICES = MoveNodeForm.mk_dropdown_tree(Category)
category = ChoiceField(choices=CHOICES)
class Meta:
model = Post
fields = ['title', 'category', 'region', 'content', ]
Suppose I have a model Car that has a field brand and a model owner that has two field: name and car_brand, whereas the latter should be one of the Car instances brands. I need to have a form where the user is presented with a text field name and a drop down select choice populated with all the brand name of Car instances. How would I achieve that?
Here is the code I am starting with. Feel free to correct. Thanks.
models.py
from django.db import models
class Car(models.Model):
brand = models.CharField(max_length=20)
class Owner(models.Model):
name = models.CharField(max_length=20)
car_brand = models.ForeignKey(Car)
forms.py
from django.forms import ModelForm, TextInput, Select
from app.models import Owner
class OwnerForm(ModelForm):
class Meta():
model = Owner
fields = ("name", "car_brand")
widgets = {
"name" : TextInput(attrs={"class" : "name"}),
"car_brand" : Select(attrs={"class" : "car_brand"}),
}
You could probably just define a __unicode__ method on your Car model and I think it should work fine. As Daniel mentioned, the form might be getting confused since you've overridden the widgets. I could be wrong, but I thought django automatically rendered attributes on form elements that can be used for styling purposes. Maybe you don't need to override the widgets. If not, you can specify the form field explicitly:
class OwnerForm(ModelForm):
car_brand = forms.ModelChoiceField(
queryset=Car.objects.all(),
widget=Select(attrs={'class': 'car_brand'}),
)
class Meta:
model = Owner
fields = ('name', 'car_brand')
widgets = {
'name': TextInput(attrs={'class': 'name'})
}
As a side note, is there any reason you don't have a CarBrand model and a foreign key field relating the Car model to it? That would be a more normalized approach to modeling your data.
I have a form class which takes a model, meta class of the form is as below,
the problem is that I want to make the patient_signature and worker_signature fields unrequired, I tried removing the class wide required_css_class but that did not help, giving each attribute classes required as True/False is also not helping.
Any suggestions...?
class Meta:
model = Locator
exclude = ('patient','worker', 'mode_of_transmission', 'secondary_telephone_number', 'locator', 'grant', 'thumbnail')
creation_date=forms.DateField(initial=datetime.date.today,
widget=SelectDateWidget(),
label="Creation Date")
patient_signature=forms.CharField(widget=ClientSignatureWidget())
worker_signature=forms.CharField(widget=WorkerSignatureWidget())
required_css_class = 'required'
Assuming you are talking about a ModelForm, you cannot override the fields inside the Meta class. It must be outside.
Also, if the field is required in the model but not in the form, then you must provide a default value, like this:
class LocatorForm:
patient_signature = forms.CharField(widget=forms.HiddenInput(), initial=" ")
class Meta:
...
Alternatively, do not mention that field in the fields list and set a value by overriding the submission of the form's POST.
patient_signature=forms.CharField(widget=ClientSignatureWidget(), required=False)
I have a model registered on the admin site. One of its fields is a long string expression. I'd like to add custom form fields to the add/update pages of this model in the admin. Based on the values of these fields I will build the long string expression and save it in the relevant model field.
How can I do this?
I'm building a mathematical or string expression from symbols. The user chooses symbols (these are the custom fields that are not part of the model) and when they click save then I create a string expression representation from the list of symbols and store it in the DB. I don't want the symbols to be part of the model and DB, only the final expression.
Either in your admin.py or in a separate forms.py you can add a ModelForm class and then declare your extra fields inside that as you normally would. I've also given an example of how you might use these values in form.save():
from django import forms
from yourapp.models import YourModel
class YourModelForm(forms.ModelForm):
extra_field = forms.CharField()
def save(self, commit=True):
extra_field = self.cleaned_data.get('extra_field', None)
# ...do something with extra_field here...
return super(YourModelForm, self).save(commit=commit)
class Meta:
model = YourModel
To have the extra fields appearing in the admin just:
Edit your admin.py and set the form property to refer to the form you created above.
Include your new fields in your fields or fieldsets declaration.
Like this:
class YourModelAdmin(admin.ModelAdmin):
form = YourModelForm
fieldsets = (
(None, {
'fields': ('name', 'description', 'extra_field',),
}),
)
UPDATE:
In Django 1.8 you need to add fields = '__all__' to the metaclass of YourModelForm.
It it possible to do in the admin, but there is not a very straightforward way to it. Also, I would like to advice to keep most business logic in your models, so you won't be dependent on the Django Admin.
Maybe it would be easier (and maybe even better) if you have the two seperate fields on your model. Then add a method on your model that combines them.
For example:
class MyModel(models.model):
field1 = models.CharField(max_length=10)
field2 = models.CharField(max_length=10)
def combined_fields(self):
return '{} {}'.format(self.field1, self.field2)
Then in the admin you can add the combined_fields() as a readonly field:
class MyModelAdmin(models.ModelAdmin):
list_display = ('field1', 'field2', 'combined_fields')
readonly_fields = ('combined_fields',)
def combined_fields(self, obj):
return obj.combined_fields()
If you want to store the combined_fields in the database you could also save it when you save the model:
def save(self, *args, **kwargs):
self.field3 = self.combined_fields()
super(MyModel, self).save(*args, **kwargs)
Django 2.1.1
The primary answer got me halfway to answering my question. It did not help me save the result to a field in my actual model. In my case I wanted a textfield that a user could enter data into, then when a save occurred the data would be processed and the result put into a field in the model and saved. While the original answer showed how to get the value from the extra field, it did not show how to save it back to the model at least in Django 2.1.1
This takes the value from an unbound custom field, processes, and saves it into my real description field:
class WidgetForm(forms.ModelForm):
extra_field = forms.CharField(required=False)
def processData(self, input):
# example of error handling
if False:
raise forms.ValidationError('Processing failed!')
return input + " has been processed"
def save(self, commit=True):
extra_field = self.cleaned_data.get('extra_field', None)
# self.description = "my result" note that this does not work
# Get the form instance so I can write to its fields
instance = super(WidgetForm, self).save(commit=commit)
# this writes the processed data to the description field
instance.description = self.processData(extra_field)
if commit:
instance.save()
return instance
class Meta:
model = Widget
fields = "__all__"
You can always create new admin template, and do what you need in your admin_view (override the admin add URL to your admin_view):
url(r'^admin/mymodel/mymodel/add/$','admin_views.add_my_special_model')
If you absolutely only want to store the combined field on the model and not the two seperate fields, you could do something like this:
Create a custom form using the form attribute on your ModelAdmin. ModelAdmin.form
Parse the custom fields in the save_formset method on your ModelAdmin. ModelAdmin.save_model(request, obj, form, change)
I never done something like this so I'm not completely sure how it will work out.
The first (highest score) solution (https://stackoverflow.com/a/23337009/10843740) was accurate, but I have more.
If you declare fields by code, that solution works perfectly, but what if you want to build those dynamically?
In this case, creating fields in the __init__ function for the ModelForm won't work. You will need to pass a custom metaclass and override the declared_fields in the __new__ function!
Here is a sample:
class YourCustomMetaClass(forms.models.ModelFormMetaclass):
"""
For dynamically creating fields in ModelForm to be shown on the admin panel,
you must override the `declared_fields` property of the metaclass.
"""
def __new__(mcs, name, bases, attrs):
new_class = super(NamedTimingMetaClass, mcs).__new__(
mcs, name, bases, attrs)
# Adding fields dynamically.
new_class.declared_fields.update(...)
return new_class
# don't forget to pass the metaclass
class YourModelForm(forms.ModelForm, metaclass=YourCustomMetaClass):
"""
`metaclass=YourCustomMetaClass` is where the magic happens!
"""
# delcare static fields here
class Meta:
model = YourModel
fields = '__all__'
This is what I did to add the custom form field "extra_field" which is not the part of the model "MyModel" as shown below:
# "admin.py"
from django.contrib import admin
from django import forms
from .models import MyModel
class MyModelForm(forms.ModelForm):
extra_field = forms.CharField()
def save(self, commit=True):
extra_field = self.cleaned_data.get('extra_field', None)
# Do something with extra_field here
return super().save(commit=commit)
#admin.register(MyModel)
class MyModelAdmin(admin.ModelAdmin):
form = MyModelForm
You might get help from my answer at :
my response previous on multicheckchoice custom field
You can also extend multiple forms having different custom fields and then assigning them to your inlines class like stackedinline or tabularinline:
form =
This way you can avoid formset complication where you need to add multiple custom fields from multiple models.
so your modeladmin looks like:
inlines = [form1inline, form2inline,...]
In my previous response to the link here, you will find init and save methods.
init will load when you view the page and save will send it to database.
in these two methods you can do your logic to add strings and then save thereafter view it back in Django admin change_form or change_list depending where you want.
list_display will show your fields on change_list.
Let me know if it helps ...
....
class CohortDetailInline3(admin.StackedInline):
model = CohortDetails
form = DisabilityTypesForm
...
class CohortDetailInline2(admin.StackedInline):
model = CohortDetails
form = StudentRPLForm
...
...
#admin.register(Cohort)
class CohortAdmin(admin.ModelAdmin):
form = CityInlineForm
inlines = [uploadInline, cohortDetailInline1,
CohortDetailInline2, CohortDetailInline3]
list_select_related = True
list_display = ['rto_student_code', 'first_name', 'family_name',]
...