django 使用django-bootstrap4插件时,使表单呈2列或其他列分布时的写法

发布时间 2023-03-22 21:13:41作者: lisicn

前言

django 使用django-bootstrap4插件时,使表单呈2列或其他列分布时的写法。
在django-bootstrap4中没有内置的方法设置表单内容成几列分布,这里采用bootstrap4的栅格布局实现效果

具体操作

  • forms.py

    class RegisterForm(UserCreationForm):
    username = CustomCharField(label="Username", help_text="Only letters can be entered!<br> For login.",widget=forms.TextInput(attrs={"id":"register_username","autocomplete":"new-username"}))
    password1 = CustomCharField(label="Password",widget=forms.PasswordInput(attrs={'autocomplete': 'new-password',"id":"register_password"}),help_text=password_validation.password_validators_help_text_html(),)
    password2 = CustomCharField(label="Password confirmation",widget=forms.PasswordInput(attrs={'autocomplete': 'new-password'}),help_text=("Enter the same password as before, for verification."),)
    first_name = CustomCharField(label="First name")
    last_name = CustomCharField(label="Last name")
    email = CustomCharField(label="Email",widget=forms.EmailInput())
    
    gender = CustomCharField(label="Gender", widget=forms.Select(choices=(("N","--"),("W","Women"),("M","Man"))))
    contact_number = CustomCharField(label="Contact Number", widget=forms.TextInput())
    address = CustomCharField(label="Address", widget=forms.TextInput())
    
    class Meta:
    	model = User
    	fields = ("username","first_name","last_name", "gender","password1", "password2","contact_number","email","address")
    
    def save(self, commit=True):
    	user = super(UserCreationForm, self).save(commit=False)
    
    	user.set_password(self.cleaned_data['password1'])
    
    	if commit:
    		user.save()
    
    		client_obj = models.Client(**{"user": user,
    									  "gender": self.data["gender"],
    									  "contact_number": self.data["contact_number"],
    									  "address": self.data["address"]
    									  })
    		client_obj.save()
    	return user
    
  • views.py传给template

  • index.html

    <form method="post" action="{% url 'register' %}">
    	<div class="row row-cols-2 row-cols-md-2">
    		{% csrf_token %}
    		{% bootstrap_form register_form %}
    	</div>
    	<div class="modal-footer">
    		<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
    		<button type="button" class="btn btn-primary" onclick="SubmitRegister()">Register
    		</button>
    	</div>
    </form>
    <-javascript-!>
    <script>
    	$(".form-group").addClass("col-6")
    </script>