How to customize Django ModelForm fields? - django

Hi I am trying to customize my ModelForm in Django. The form looks like this:
class RegistrationForm(forms.ModelForm):
class Meta:
model = Registration
fields = ['name', 'age', 'details'......]
I am trying to add different classes to different fields, along with placeholders and no labels. How do I do that? Is there a way to carry this out in the templates?

You can add class and other parameters to a field using widget
class RegistrationForm(forms.ModelForm):
name = forms.CharField(label=' ',widget=forms.TextInput(attrs={'class':'textClass','placeholder':'Enter Name'}))
details = forms.CharField(widget=forms.Textarea(attrs={'class':'special','maxlength':'100'}))
class Meta:
model = Registration
fields = ['name', 'age', 'details'......]
For brief explanation: Documentation

Related

DRF APIView - How can I add help text to auto generated form?

I am working with Django Rest Framework and using APIView and serializer form to add new data. I want to add some help text to the form as tooltip. Since the form is auto generated, I need some help on how can I add this to the form. I am using ModelSerializer.
This is how my serializer looks like
class MySerializer(serializers.ModelSerializer):
class Meta:
Model = MyModel
fields = ('id','name', ...)
My form fields should have help texts. How can I add them? Thanks!
Specify help_text as additional keyword argument (see documentation) instead declaring a serializer field specifying all options that are already in the model field (unique, null, max_length etc.)
class MySerializer(serializers.ModelSerializer):
class Meta:
model = MyModel
fields = ('id','name', ...)
extra_kwargs = {
'name': {
'help_text': 'You help text here...'
}
}
You could add the help text using help_text argument of serializer field
class MySerializer(serializers.ModelSerializer):
name = serializers.CharField(help_text="foo bar")
class Meta:
Model = MyModel
fields = ('id','name', ...)
you can add help_text attribute in models.py
name = models.CharField(max_length=60, help_text="Your help text here....")
More Info...

Django multiple Admin Model

I Wanna use 2 Admin apps such as :
django-admin-sortable
django-import-export
Is there a way to use both in Admin Form ?
I mean my code is using SortableAdmin:
class RuleAdminForm(forms.ModelForm):
content = forms.CharField(widget=CKEditorWidget())
class Meta:
model = Rule
fields = '__all__'
class RuleAdmin(SortableAdmin):
list_display = ('title', 'section', 'subsection',)
readonly_fields = ('author', 'date_posted')
fields = ('title', 'section', 'subsection', 'content', 'author', 'date_posted')
form = RuleAdminForm
with .register(Rule, RuleAdmin)
If I want to use import-export I need to create this :
class RuleResource(resources.ModelResource):
class Meta:
model = Rule
class RuleResourceAdmin(ImportExportModelAdmin):
resource_class = RuleResource
But I can't register with .register(Rule, RuleResourceAdmin) since Rule is already registered
Is there a way to have both options ? Using sortable admin to sort my rules, and the possibility to import CSV etc.
Many thanks !
Using of proxy model.
class RuleProxyModel(Rule):
class Meta:
proxy = True
admin.site.register(RuleProxyModel,RuleResourceAdmin)
How to use proxy model

djangrestframework to display model in foreign key

Please excuse the title. Im not quite sure how ask this question without just showing.
In django I have two models.
class people(models.Model):
name=models.TextField(max_length=100)
nickname=models.TextField(max_length=100)
class visits(models.Model):
person=models.OneToOneField(people)
visitdate=models.DateTimeField(auto_now=True)
and then a serializer for the restapi.
#serializers.py
class VisitsSerializer(serializers.ModelSerializer):
class Meta:
model = visits
fields=("id","person","date")
When the API returns the dictionary, it looks like this.
{id:1,person:1,visitdate:11/23/17}
Is there a way to make the API return the actual values that are associated with the person with id 1? like so.
{id:1,person:{id:1,name:foo,nickname:bar},visitdate:11/23/17}
Try creating a serializer class for People and then add this to your visit serializer:
people = PeopleSerializer(read_only = True)
then add it(people) to fields in the Meta class, and just a suggestion, try making it a foreign key instead of a OnetoOne Relationship
You can do that with nested relationship. Here is an example:
class PersonSerializer(serializers.ModelSerializer):
class Meta:
model = people
fields = ('name', 'nickname')
class VisitsSerializer(serializers.ModelSerializer):
person = PersonSerializer(read_only=True)
class Meta:
model = visits
fields = ("id", "person", "date")
Documentation on nested serializers is here.
The Corresponding Serializer would be as follows:
class PersonSerializer(serializers.ModelSerializer):
class Meta:
model = people
class VisitsSerializer(serializers.ModelSerializer):
person = serializers.SerializerMethodField()
class Meta:
model = visits
fields = ('id', 'person', 'date')
def get_person(self, obj):
return PersonSerializer(obj.person).data

Restricted set of nested fields in a django REST framework ModelSerializer

Consider the following serializer
class MyModelSerializer(serializers.ModelSerializer):
class Meta:
model = MyModel
fields = ('id', 'account')
depth = 1
The field account refers to a ForeignKey in MyModel and I want to expose some of the Account fields with this serializer but not all of them.
How do I specify that only account.name and account.email should be serialized?
You can do this by creating your own serializer to use as the nested serializer.
class AccountSerializer(serializers.ModelSerializer):
class Meta:
model = Account
fields = ('name', 'email', )
You are better off with creating specialized serializers instead of relying on Django REST Framework to create them for you. By default, serializers that are automatically created contain all fields defined on the model.
class MyModelSerializer(serializers.ModelSerializer):
account = AccountSerializer()
class Meta:
model = MyModel
fields = ('id', 'account', )
You can find out more about nested serializers in the Django REST Framework documentation.

django use model choices in modelform

I was wondering how i should use my model choices options, in my ModelForm.
Example(model):
class NPCGuild(models.Model):
CATEGORIES=(
('COM', 'Combat'),
('CRA', 'Crafting'),
('WAR', 'Warfare'),
)
faction = models.ForeignKey(Faction)
category = models.CharField(max_length=3, choices=CATEGORIES)
name = models.CharField(max_length=63)
My Form:
class NPCGuildForm(forms.ModelForm):
name = forms.CharField()
category = forms.CharField(
some widget?)
faction_set = Faction.objects.all()
faction = forms.ModelChoiceField(queryset=faction_set, empty_label="Faction", required=True)
class Meta:
model = NPCGuild
fields = ['name', 'category', 'faction']
As you can see, im not sure what i should be doing to get my choices from my model as a choicefield. Maybe it can be done with a ModelChoiceField as well, but then how to get the choices in it?
You should specify model in the Meta class and fields will be generated automatically:
class NPCGuildForm(forms.ModelForm):
class Meta:
model = NPCGuild
You can add extra form fields if you want to. Read more about ModelFroms.
Update As karthikr mentioned in the comment. If you want to set available choices in a form field, you have to use forms.ChoiceField, like this:
category = forms.ChoiceField(choices=NPCGuild.CATEGORIES)
I will do it differently, just keep in mind that you can generate the whole form from the model automatically, without having to create each field again, and this is one of the beauty of Django which save you time, here is how I will do it, in your form file:
class NPCGuildForm(forms.ModelForm):
class Meta:
model = NPCGuild
fields = ['name', 'category', 'faction']
widgets = {
'category' : forms.Select()
}