Home > Net >  how can I customize auto generated django form?
how can I customize auto generated django form?

Time:06-09

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.

CodePudding user response:

you can use widgets, https://docs.djangoproject.com/en/4.0/ref/forms/widgets/ ,this is 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"}),            
            }
  • Related