Home > Blockchain >  Change class for CreateView Django
Change class for CreateView Django

Time:10-30

I have CreateView and I want add class for fields views.py:

class CreatePost(CreateView):
    model = apps.blog.models.Post
    fields = ['name', 'content', 'photo']
    template_name = 'cabinet/post/create.html'

and in template:

{% extends 'cabinet/includes/main.html' %}
{% block title %}Створити новину{% endblock %}
{% block content %}
    <form action="." method="POST">
        {% csrf_token %}
        {{ form.media }}
        {{ form.as_ul }}
    </form>
{% endblock %}

And in output I have

<p><label for="id_name">Name:</label> <input type="text" name="name" maxlength="250" required="" id="id_name"></p>

but I want have <input type="text" name="name" maxlength="250" required="" id="id_name">

CodePudding user response:

You can define a ModelForm where you specify the for (certain) widgets:

# app_name/forms.py

from apps.blog.models import Post
from django import forms

class PostForm(forms.ModelForm):
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['name'].widget.attrs['class'] = 'form-control'

    class Meta:
        model = Post
        fields = ['name', 'content', 'photo']

Then we can use that form in our CreatePostView:

class CreatePostView(CreateView):
    model = apps.blog.models.Post
    form_class = PostForm
    template_name = 'cabinet/post/create.html'

Note: In Django, class-based views (CBV) often have a …View suffix, to avoid a clash with the model names. Therefore you might consider renaming the view class to CreatePostView, instead of CreatePost.

  • Related