Django中基于类的视图中的样式表单字段

时间:2018-10-25 05:08:07

标签: django

我正在使用基于类的视图在网站上创建表单。到目前为止,以下代码可以正常工作。但是我需要在box-message字段中添加自定义CSS类(message),以便可以正确设置样式。我该怎么办?

这是我到目前为止所完成的。

# view.py ----

from django.views.generic.edit import CreateView
from .models import CandidateInfo

class PostForm(forms.ModelForm):
    class Meta:
        model = CandidateInfo
        fields = ("name", "email", "message")

class ContactView(CreateView):
    form_class = PostForm
    model = CandidateInfo
    template_name = "index_test.html"


# models.py ----

from django.db import models
from django.urls import reverse


class CandidateInfo(models.Model):
    name = models.CharField(max_length=200)
    email = models.CharField(max_length=200)
    message = models.TextField()

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse("index_text")

和模板:

<form id="contact-us" action="" method="post">{% csrf_token %}

{{ form.as_p }}

<input type="submit" name="submit" id="contact-button" value="Send" />

这是生成的HTML:

<p><label for="id_name">Name:</label> <input type="text" name="name" maxlength="200" required="" id="id_name"></p>
<p><label for="id_email">Email:</label> <input type="text" name="email" maxlength="200" required="" id="id_email"></p>
<p><label for="id_message">Message:</label> <textarea name="message" cols="40" rows="10" required="" id="id_message"></textarea></p>

我需要的是让textarea标记具有box-message类。

2 个答案:

答案 0 :(得分:1)

尝试一下:

class PostForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['message'].widget.attrs.update({'class': 'box-message'})

    class Meta:
    model = CandidateInfo
    fields = ("name", "email", "message")

详细了解以下内容: Django Form Widgets

答案 1 :(得分:1)

将此添加到您的邮寄表单中,

class PostForm(form.ModelForm):
    message = forms.CharField(widget = forms.Textarea(attrs={'class':'#add class name', 'placeholder':'If you require'}))

    class Meta:
         #rest