设置 Django CreateView 表单的样式

问题描述 投票:0回答:1

我想设计类似选项B的表单,如图所示,但无法获得结果我的表单看起来像A。我没有使用任何 FormModelForm,只是使用 CreateView。我也不想修改我的 Views 或添加任何 FormClass 所以请让我如何获得结果。

这是我的模型

class InfluencerModel(models.Model):
    full_name = models.CharField(max_length=255, null=False, blank=False)
    email = models.EmailField(max_length=255, null=False, blank=False)
    contact_number = models.CharField(max_length=10, null=False, blank=False)
    instagram_id   = models.CharField(max_length=50, null=False, blank=False)
    message = models.TextField(null=True, blank=True)
    visited_on = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.email

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

Views.py

class InfluencersPageView(CreateView):
    model = InfluencerModel
    template_name = 'home/influencers.html'
    fields = ['full_name', 'email', 'contact_number', 'instagram_id', 'message']

    def get_context_data(self, *args, **kwargs):
        context = super(InfluencersPageView, self).get_context_data(*args, **kwargs)
        return context

这是模板

<form action="" role="form" class="php-email-form" method="post"> {% csrf_token %}
  <div class="row">
    <div class="col-md-6 form-group">
      {{ form.full_name.errors }}
      {{form.full_name|as_crispy_field}}
    </div>

    <div class="col-md-6 form-group mt-3 mt-md-0">
         {{ form.email.errors }}
         {{form.email|as_crispy_field}}

    </div>


  <div class="form-group col-md-6">
    {{ form.contact_number.errors }}
    {{form.contact_number|as_crispy_field}}
  </div>

  <div class="form-group col-md-6">
    {{ form.instagram_id.errors }}
    {{form.instagram_id|as_crispy_field}}
  </div>

      </div>



  <div class="form-group mt-3" rows="7">
    {{ form.message.errors }}
    {{form.message|as_crispy_field}}

  </div>

   <div class="text-center">
    <button type="submit" class="btn btn-outline-secondary" style="background-color:#FF512F; color: white">Send Message</button>
 </div>

</form>

html python-3.x django django-models django-views
1个回答
0
投票

看起来您正在使用脆皮表格包。请务必将其加载到您使用它的任何表单上方,如下所示:

{% load crispy_forms_tags %}

{{form.some_field|as_crispy_field}}

除此之外,获得所需结果的其他一些方法是将自定义 CSS 应用于表单字段。例如,如果您使用引导程序,

<style>
.form-control {
    background-color: rgb(200,200,200);
}
.form-control:focus {
    background-color: yellow; 
}
</style>

...将为您提供一些不同的输入样式。最后,您可以使用表单类并更改字段小部件上文本框的高度,例如:


class SomeFormClass(forms.ModelForm):

    class Meta:
       model = MyModelClass
       fields = ['message'] # add more as needed

    message = forms.CharField(required=False, widget=forms.Textarea(attrs={"rows":3, "cols":20})) # rows is adjusting the height of the message field.

这些只是设置表单输入样式的几种方法。

© www.soinside.com 2019 - 2024. All rights reserved.