Home > Net >  Render html form in django with forms.py
Render html form in django with forms.py

Time:09-13

I have django web application with authentication system in it. I have user registration view, customer model and

UserCreationForm in forms.py:

class CustomerSignUpForm(UserCreationForm):
    first_name = forms.CharField(required=True)
    last_name = forms.CharField(required=True)
    # phone_number = forms.CharField(required=True)
    # location = forms.CharField(required=True)

    class Meta(UserCreationForm.Meta):
        model = User
    
    @transaction.atomic
    def save(self):
        user = super().save(commit=False)
        user.is_customer = True
        user.first_name = self.cleaned_data.get('first_name')
        user.last_name = self.cleaned_data.get('last_name')
        print(user.last_name)
        user.save()
        customer = Customer.objects.create(user=user)
        # customer.phone_number=self.cleaned_data.get('phone_number')
        # customer.location=self.cleaned_data.get('location')
        customer.save()
        return user

My model looks like this:

...
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    phone_number = models.CharField(max_length=20)
    location = models.CharField(max_length=20)

I render form in my customer_register.html:

...
<section>
        <div >
          <div >
            <div >
              <div >
                <div >
                  <h2>Register</h2>
                </div>
                <div >
                    <form action="{% url 'customer_register' %}" method="POST" novalidate>
                      {% csrf_token %}
                        {% for field in form.visible_fields %}
                           <div >
                               {{ field.label_tag }}
                                  {% render_field field  %}
                                    {% for error in field.errors %}
                                      <span style="color:red">{{ error }}</span>
                                    {% endfor %}
                         {% endfor %}
                          </div>
                    </form>
                 </div>
                    </div>   
                </div>
              </div>
            </div>
        </div>
      </section>
...

It doesn't look very pretty though.

What I want to do is to replace my form in customer_register.html with new form in which I wouldn't use widget_tweaks but just html.

CodePudding user response:

I'm moderately confused with what you mean by "wouldn't use widget_tweaks but just html"


but if the form isn't pretty you can always render/place the form fields yourself doing something like:

<form action="{% url 'customer_register' %}" method="POST" novalidate>
  <div >
    <div >
      <b>First Name:<b>
      {{ form.first_name }}
      {% if 'first_name' in error %}
        <div style='color:red'>{{error.first_name.0.message}}</div>
      {% endif %}
    </div>
    <div >
      <b>Last Name:<b>
      {{ form.last_name }}
      {% if 'last_name' in error %}
        <div style='color:red'>{{error.last_name.0.message}}</div>
      {% endif %}
    </div>
  </div>
</form>

You could also add classes in the Forms.py __init__ functions, and then add some CSS to make it look pretty (I assume this is the Widget Tweaking, but i don't see it in your original form

class CustomerSignUpForm(UserCreationForm):
    first_name = forms.CharField(required=True)
    last_name = forms.CharField(required=True)
    # phone_number = forms.CharField(required=True)
    # location = forms.CharField(required=True)

    def __init__(self,  *args, **kwargs):
        super(CustomerSignUpForm, self).__init__(*args, **kwargs)
        self.fields['first_name'].widget.attrs={'class': 'form-control'}
        self.fields['last_name'].widget.attrs={'class': 'form-control'}

or you could just straight up create the HTML fields yourself.. All the form and the backend care about is the 'name' attribute- but! You lose all the dynamic validation that Django does.. sooooo I recommend doing the 1st one

<form action="{% url 'customer_register' %}" method="POST" novalidate>
  <div >
    <div >
      <b>First Name:<b>
      <input type="text" name="first_name" max_length="100" required ></input>
      {% if 'first_name' in error %}
        <div style='color:red'>{{error.first_name.0.message}}</div>
      {% endif %}
    </div>
    <div >
      <b>Last Name:<b>
      <input type="text" name="last_name" max_length="100" required ></input>
      {% if 'last_name' in error %}
        <div style='color:red'>{{error.last_name.0.message}}</div>
      {% endif %}
    </div>
  </div>
</form>
  • Related