Writing a Django Form while keeping HTML styling

I have a Django form that I have created manually in order to keep the format of the styling, but I realized that the form is compromised of several inputs and manually is taking too long to change each.

I am also able to generate the form automatically using {{ form.as_p }} but I lose the HTML style format that I have below. Is there an easy way to make it instead of manually changing each input?

This is the original HTML template that I am trying to keep

        </button>
          <div class="form-outline mb-4">
            <input
              type="text"
              id="businessName"
              class="form-control"
              name="businessName"
            />
            <label class="form-label" for="typeText"
              >Legal Business Name</label>
          </div>

Here is the working Django form:

      {% if submitted %}
      Your forms has been submitted
      {% else %}
      <form method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <!-- Submit button -->
        <button
          type="submit"
          class="btn btn-primary btn-block mb-4"
          id="btn"
        >
          Submit
        </button>

      </form>

Here is the views.py

def add_form(request):
    submitted=False
    if request.method == 'POST':
        form = infoForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/?submitted=True')
    else:
        form = infoForm()
        if 'submitted' in request.GET:
            submitted=True
    return render(request, 'template/template.html',{'form':form, 'submitted':submitted})

Here is the form

class infoForm(ModelForm):
    class Meta:
        model = Info
        fields = ['businessName']

Here is what I have tried:

                    <div class="form-outline mb-4">
                        <input type="text" class="form-control" name="businessName" {% if form.is_bound %}value="{{ form.businessName.value }}"{% endif %}>
                        <label class="form-label">Legal Business Name</label>
                    </div>
                    {% for err in form.businessName.errors %}
                        <small class="text-danger mb-2 ml-2">{{ err }}</small>
                    {% endfor %}

My Question: How to keep the same HTML styling while making it easy by using {{ form.as_p }}?

What is the required input for attributes in this case?



Read more here: https://stackoverflow.com/questions/68463200/writing-a-django-form-while-keeping-html-styling

Content Attribution

This content was originally published by Etchosh at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: