I decided to organize my page using two separated forms to build a single model:
class MandateForm1(forms.ModelForm):
class Meta:
model = Mandate
fields = ("field_a", "field_b"),
class MandateForm2(forms.ModelForm):
class Meta:
model = Mandate
fields = ("field_c", "field_d"),
In my view, I would get something like:
form_1 = MandateForm1(request.POST)
form_2 = MandateForm2(request.POST)
This way, how can I create my model using Form save() method?
As a current workaround, I'm using Mandate.objects.create(**form_1.cleaned_data, **form_2.cleaned_data). The drawback is I need to handle M2M manually with this method.
Thanks.
The way you have phrased the question, this is all being submitted in the same POST from a single page. If that's true, you might be able to do something like:
if request.method == "POST" and form1.is_valid() and form2.is_valid():
form1.instance.field_c = form2.instance.field_c
form1.instance.field_d = form2.instance.field_d
form1.save()
Lets say that we have two models: ModelA and ModelB.
I will use Django-Tables2 to create a table out of these models.
In tables.py you could have two separate table classes (below).
from .models import ModelA, ModelB
import django_tables2 as tables
class ModelATable(tables.Table):
class Meta:
#some basic parameters
model = ModelA
#the template we want to use
template_name = 'django_tables2/bootstrap.html'
class ModelBTable(tables.Table):
class Meta:
#some basic parameters
model = ModelB
#the template we want to use
template_name = 'django_tables2/bootstrap.html'
This means there will be a table for each model. However I think a more efficient coding solution would be to something as follows.
class MasterTable(tables.Table, request):
#where request is the HTML request
letter = request.user.letter
class Meta:
#getting the correct model by doing some variable formatting
temp_model = globals()[f'Model{letter}']
#some basic parameters
model = temp_model
#the template we want to use
template_name = 'django_tables2/bootstrap.html'
The issue involves passing the request object in the table definition from views.py. It would look something like:
def test_view(request):
#table decleration with the request object passed through...
table = MasterTable(ModelOutput.objects.all(), request)
RequestConfig(request).configure(table)
return render(request, 'some_html.html', {'table': table})
I do not know how to pass through a variable, in this case the request object, to the class so that variable formatting can be done.
I think you are looking for table_factory. This returns a Table class for you which you can use. (Also note, django.apps.apps.get_model is a better way of looking up a model than using globals.)
from django_tables2 import tables
from django.apps import apps
class BaseTable(tables.Table):
class Meta:
template_name = 'django_tables2/bootstrap.html'
def test_view(request):
temp_model = apps.get_model('myapp', f'Model{request.user.letter}')
MasterTable = tables.table_factory(temp_model, table=BaseTable)
table = MasterTable(ModelOutput.objects.all())
RequestConfig(request).configure(table)
return render(request, 'some_html.html', {'table': table})
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 would like to seek assistance and guidance to my problem.
I have the following models:
class myinfo(models.Model):
name = models.CharField(max_length=30, null=True)
class mynumbers(models.Model):
fkey = models.ForeignKey("myinfo")
Job_Position = models.CharField(max_length=30, null=True)
The mynumbers model is dynamically generated via django-dynamic-formset.
My form
class info(ModelForm):
name= forms.CharField( max_length=20)
class Meta:
model = APPLICANT_DATA
fields = ('name',)
class numbers(ModelForm):
number = forms.CharField( max_length=20)
class Meta:
model = APPLICANT_DATA
fields = ('number',)
If you want to save your dynamic form fields you have to do this in views
for field in formset:
field.save()
My views:
def index(request):
aformset = formset_factory(numbers)
formset = aformset(request.POST)
form = info(request.POST)
if request.method == 'POST':
if form.is_valid():
if formset.is_valid():
for field in formset:
formset.save()
form.save()
But the problem starts when my dynamically generated field has a foreign key(mynumbers) which raises an error must be a myinfo instance. How would I save the 2 forms where mynumbers has a foriegn key to myinfo? Is there a better way to what I did? Thank you in advance,
This is where inlineformset_factory would be used. This allows you to have a parent model and a number of child models (related w/ parent via a foreignkey) and save them together. There are many arguments that can be passed to the inlineformset_factory in order to customize behavior (such as the minimum and maximum number of inline forms allowed, whether the user can delete inline forms, etc.) but the crux is shown below.
# views.py
from django.forms.models import inlineformset_factory
from my_app.forms import numbers as NumberForm
from my_app.forms import info as InfoForm
from my_app import models
myFormset = inlineformset_factory(models.myinfo,
models.mynumbers,
form=NumberForm
)
def index(request):
if request.POST:
form = InfoForm(request.POST)
if form.is_valid():
info = form.save(commit=False)
formset = myFormset(request.POST, instance=info)
if formset.is_valid():
info.save()
formset.save()
return HttpResponse('saved successfully')
else:
form = InfoForm()
formset = myFormset(instance=models.myinfo())
return render_to_response("recipes/submit.html", {
"form": form,
"formset":formset,
},
context_instance=RequestContext(request))
Please note: In your question, you typed for field in formset: formset.save(). A formset is a collection of forms, not a collection of fields.
Formsets can be tricky and require the template rendered correctly with additional template components that are not part of regular forms (such as the management_form variable that allows for Django to properly process what has been added/deleted/moved/changed). It's definitely worth doing some tutorials in order to get an idea of best practices so that you don't go down a troubleshooting rabbithole w/ your custom implementation.
I suggest this post from Charles Leifer as a good entry to get acquainted with the basics.
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',]
...