Django ModelForm with User data in Generic View - python

I have a model with a foreign key to group (the other fields don't matter):
class Project(models.Model) :
group = models.ForeignKey(Group)
...
I have a model form for this model:
class AddProjectForm(forms.ModelForm):
class Meta:
model = Project
fields = ["group","another"]
In my urls, I am using this in a generic view:
(r'^$', create_object, {'form_class':AddProjectForm, 'template_name':"form.html", 'login_required':True, 'extra_context':{'title':'Add a Project'}}),
That all works, but I want to have the group field display only the groups that the current user belongs to, not all of the groups available. I'd normally do this by passing in the user to the model form and overriding init if I wasn't in a generic view. Is there any way to do this with the generic view or do I need to go with a regular view to pass in that value?

This is gonna look dirty, since the generic view instantiates the form_class with no parameters. If you really want to use the generic_view you're gonna have to generate the class dynamically :S
def FormForUser(user):
class TmpClass(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(TmpClass, self).__init__(*args, **kwargs)
self.fields['group'].queryset = user.group_set.all()
class Meta:
model = Project
fields = ['group', 'another']
Then wrap the create object view
#login_required # Only logged users right?
def create_project(request):
user = request.user
form_class = FormForUser(user)
return create_object(request, form_class=form_class, ..... )
My recommendation is to write your own view, it will give you more control on the long term and it's a trivial view.

No, you'll need to make a regular view. As can be seen by looking at the source code for create_object(), there's no functionality to pass in extra parameters to the modelform (in django 1.2):
http://code.djangoproject.com/svn/django/branches/releases/1.2.X/django/views/generic/create_update.py

Related

adjust forms that are generated by django generic editing views

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

Django UpdateView: define fields dynamically via function instead of a member variable

I have a really simple UpdateView, where my fields are defined by the member variable fields
class DataUpdateView(generic.edit.UpdateView):
template_name = 'data/edit.html'
model = Data
fields = ['title', 'text']
text2 = forms.CharField(widget=forms.Textarea)
success_url = reverse_lazy('data:index')
Now I have the situation that I want to change the fields value depending on a special user permission, but I have no idea how I can define the fields via a function (or any better option).
Is that possible with Django (I'm using the latest version)
Greetings
Tonka
Surely you can. This is a regular class-based view, wich means you should be able to override its methods like get and post and modify fields there.
In this case you want to set fields on all type of requests, so adding dispatch method should be the right choice:
class DataUpdateView(generic.edit.UpdateView):
template_name = 'data/edit.html'
model = Data
fields = ['title', 'text']
text2 = forms.CharField(widget=forms.Textarea)
success_url = reverse_lazy('data:index')
def dispatch(self, request, *args, **kwargs):
# Check permissions for the request.user here
self.fields = ['title', 'text', 'extrafield']
return super().dispatch(request, *args, **kwargs)
Most of the class attributes used in class based views cash be set in equivalently named methods instead. In this case, you can define get_fields().

Django rest framework: override create() in ModelSerializer passing an extra parameter

I am looking for a way to properly ovverride the default .create() method of a ModelSerializer serializer in Django Rest Framework for dealing with an extra parameter.
In my original Django model I have just overridden the default.save() method for managing an extra param. Now .save() can be called also in this way: .save(extra = 'foo').
I have to create a ModelSerializer mapping on that original Django model:
from OriginalModels.models import OriginalModel
from rest_framework import serializers
class OriginalModelSerializer(serializers.ModelSerializer):
# model fields
class Meta:
model = OriginalModel
But in this way I can't pass the extra param to the model .save() method.
How can I properly override the .create() method of my OriginalModelSerializer class to take (eventually) this extra param into account?
Hmm. this might not be the perfect answer given I don't know how you want to pass this "extra" in (ie. is it an extra field in a form normally, etc)
What you'd probably want to do is just represent foo as a field on the serializer. Then it will be present in validated_data in create, then you can make create do something like the following
def create(self, validated_data):
obj = OriginalModel.objects.create(**validated_data)
obj.save(foo=validated_data['foo'])
return obj
You'd probably want to look at the default implementation of create for some of the other things it does though (like remove many-to-many relationships, etc.).
You can now do this in the view set (threw in user as a bonus ;) ):
class OriginalModelViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows OriginalModel classes to be viewed or edited.
"""
serializer_class = OriginalModelSerializer
queryset = OriginalModel.objects.all()
def perform_create(self, serializer):
user = None
if self.request and hasattr(self.request, "user"):
user = self.request.user
serializer.save(user=user, foo='foo')
That way the Serializer can stay generic, i.e.:
class OriginalModelSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = OriginalModel
fields = '__all__'

Add custom form fields that are not part of the model (Django)

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',]
...

How to customize a Queryset of a Field from a admin Inline that uses a pk of the primary form in Django?

Customizing a queryset of a form field in Django isn't a hard job. Like this
But, assuming I have the following models:
#models.py
class Work(Model):
name = models.CharfField(...)
#some fields
class Gallery(Model):
work = models.ForeignKey(Work)
class Photo(Model):
gallery = models.ForeignKey(Gallery)
class StageOfWork(Model):
work = models.ForeignKey(Work)
gallery = models.ForeignKey(Gallery)
#some fields
And an admin.py like this
#admin.py
class StageOfWorkAdmin(admin.TabularInline):
model = StageOfWork
form = StageOfWorkForm
extra = 1
class WorkAdmin(admin.ModelAdmin):
inlines = [EtapaObraAdmin]
I have this problem: when I edit a Work, exists many Form Inlines of StageOfWorks, these StageOfWorks inline forms have a Gallery selector.
I need to customize de queryset of this Galleries like this:
class StageOfWorkForm(ModelForm):
def __init__(self, *args, **kwargs):
super(StageOfWorkForm, self).__init__(*args, **kwargs)
if 'instance' in kwargs:
self.fields['gallery'].queryset = Gallery.objects.filter(work__id=self.instance.work.id)
But this only works in the Forms who is editing forms. I need to get a work id in context of init method to do the right queryset anyway.
How could I do that?
The only way I have been able to do it is pass in the data you need into the instantiaton of the form class.
i.e., in your view:
def view(request):
...
work = <whatever>
form = StageOfWorkForm(work, request.POST)
...
Then, your form needs to the work object:
class StageOfWorkForm(ModelForm):
def __init__(self, work, *args, **kwargs):
super(StageOfWorkForm, self).__init__(*args, **kwargs)
self.fields['gallery'].queryset = work.gallery_set.all()
I haven't done this exact thing, but I did something similar. I used the Smart Selects Django plugin. This can be found here: https://github.com/digi604/django-smart-selects
I've use this to a filtered select in the admin, but it was in a regular model, not an inline, but it is quite possible that the plugin works in inlines too. I'd at least check it out.
Hailey

Categories