how can I customize auto generated django form?

Question:

I’ve created a form on Django app with its builtin forms class.

here is my forms.py file.

 # import form class from django
from dataclasses import field
from django import forms

from .models import #MYMODEL#

class myForm(forms.ModelForm):
    class Meta:
        model = #MYMODEL#
        fields = "__all__"

and my view function in views.py

def index(request):
    context = {}

    form = myForm(request.POST or None, request.FILES or None)
    if form.is_valid():
        form.save()
    
    context['form'] = form
    return render(request, "index.html", context)

and finally the page (index.html) that shows the form

    <form method="POST" enctype="multipart/form-data">
        {% csrf_token %}
        {{ form.as_p }}
        <input type="submit" value="Kaydet">
    </form>

So, what I need to do is to set custom input types like text or select box since the auto-generated form includes only text inputs.

Asked By: selimhan

||

Answers:

You can use Widgets.

This is an example:

   class myForm(forms.ModelForm):
        class Meta:
            model = #MYMODEL#
            fields = "__all__"
            widgets = {            
                'category': forms.Select(attrs={"class": "form-control"}),
                'title': forms.TextInput(attrs={"class": "form-control"}),          
                'description': forms.Textarea(attrs={"class": "form-control"}),            
            }
Answered By: oruchkin
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.