Django unable to render form in table format - html

I have a django formset and I am trying to render it row by row. Instead, the form is being render column by column (like a vertical form instead of horizontal). I am using django's form.as_table but it is still not rendering correctly. Any ideads?
form.html:
<form id="formset" class="original" action="{% url 'inventory:requests' inventory.id %}" method="post">{% csrf_token %}
<!-- Add New Row -->
{{formset.management_form}}
{% for form in formset.forms %}
{{ form.non_field_errors }}
{{ form.errors}}
<div class='item'>
<table>{{ form.as_table }}</table>
<p style=""><a class="delete" href="#">Delete</a></p>
</div>
{% endfor %}
<p><a id="add" href="#">Add another item</a></p>
<input type="submit" name="submit" value="Request Blocks" id="submitButton">
</form>

The form's as_table method just uses <tr></td> instead of <div> to render your form - but it will be rendered visually the same way.
To easily get control over your form, consider using django-crispy-forms. Here is is how you would make your form render horizontally:
In your forms.py, add this (in addition to your normal code):
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
class ExampleFormSetHelper(FormHelper):
def __init__(self, *args, **kwargs):
super(ExampleFormSetHelper, self).__init__(*args, **kwargs)
self.form_method = 'post'
self.render_required_fields = True
self.template = 'bootstrap/table_inline_formset.html'
self.add_input(Submit("submit", "Save"))
Next, in your views.py:
from .forms import ExampleFormsetHelper, YourFormSet
def formset_view(request):
formset = YourFormSet()
helper = ExampleFormSetHelper()
return render(request, 'template.html',
{'formset': formset, 'helper': helper})
Finally, in your template, all you need is:
{% load crispy_forms_tags %}
{% crispy formset helper %}
For more details, the documentation has the specifics.

Related

Django Crispy Forms does not display the border of a certain field

I am using bootstrap and crispy forms to style my website.
But a border around all my username fields dont get displayed. Like shown here (I cut off some parts). It is confusing to me, as all other fields get displayed properly:
My Code (Form / HTML / View) looks like:
class LWRegisterForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = LWUser
fields = ['username', 'email', 'password1', 'password2']
.
...
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
{{ form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-dark" type="submit">{% trans "Register" %}</button>
</div>
</form>
.
...
def get(self, request):
form = LWRegisterForm()
context = {'form': form}
return render(request, 'users/register.html', context)
In order to fix it I tried in the HTML to use {% crispy update_form %} and {{ update_form.username|as_crispy_field }} instead of my code. Both still displayed it without a border.
I also tried swapping around the order of things that get displayed with
{{ update_form.email|as_crispy_field }}
{{ update_form.username|as_crispy_field }}
but still the username field was without a border.
I tried reinstalling django-crispy-forms via pip unistall. Did not work.
Now I am out of ideas. What could it be?
try something like this
i also sume you load that you form properly in template
<form method="POST" action="">
{% csrf_token %}
<div class='col-lg-6'>{{ update_form.username|as_crispy_field }}
</div>
<div class='col-lg-6'>{{ update_form.email|as_crispy_field }}</div>
</div>
<button class="btn btn-dark" type="submit">{% trans "Register" %}
</button>
</div>
</form>
if this still doesn't work for you use widgets in forms.py for giving broder to username

(Resolved)How does the html button tag work with Django template?

This is a Django template where the user submits some data through a django form to create a new "topic". I want to ask why does the html button work and submit the data I want even though I didn't specify it's type (submit, reset, or button)?
{% extends "learning_logs/base.html" %}
{% block content %}
<form action ="{% url 'learning_logs:new_topic' %}" method="post">
{% csrf_token %}
{{form.as_p}}
<button>Add Topic</button> <comment><-- why does this button still work?</comment>
</form>
{% endblock %}
Heres the views.py, if you need it.
def new_topic(request):
if request.method != 'POST':
form = TopicForm()
else:
form = TopicForm(data = request.POST)
if form.is_valid():
form.save()
return redirect('learning_logs:topic')
context = {'form':form}
return render(request, 'learning_logs/new_topic.html',context)
Answered by Abdul Aziz Barkat and Ben ( thanks to them)

Django from is not being past into html template

As in the question title "{{form}}" from is not being loaded into html template I checked by previous projects I have almost the same code, differences are required fields, naming etc. mechanic is the same.
In those projects registration function works perfectly here it's not even throwing an error just don't display anything.
No wonder what might be wrong in here.
forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from .models import Profile
class RegistrationForm(UserCreationForm):
email = forms.EmailField(max_length=60, help_text="Required field")
class Meta:
model = Profile
fields = ["email", "username", "password", "password2", "calories_plan", "diet_type"]
views.py
def registration_view(request):
context = {}
if request.POST:
form = RegistrationForm(request.POST)
if form.is_valid():
email = form.cleaned_data.get("email")
password = form.cleaned_data.get("password")
new_account = authenticate(email=email, password=password)
login(request, new_account)
else:
context["registration_form"] = form
else:
form = RegistrationForm()
context["registration_form"] = form
return render(request, "Account/registration.html", context)
html template
{% extends 'main.html' %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
<form method="post">
{% csrf_token %}
<fieldset class="form-group">
<legend class=border-bottom mb-4>Join today
{{ form }}
</legend>
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Sign Up</button>
</div>
</form>
<div class="border-top pt-3">
<small class="text-muted">
Already have an account?
<a href="#" class="ml-2">
Log In
</a>
</small>
</div>
</div>
{% endblock %}
And how it looks in browser.
You're passing 'registration_form' to the context, but in template you are calling {{ form }}.
Replace:
{{ form }}
with:
{{ registration_form }}

Why won't my UserCreationForm render in chronological order?

I want the form to show
Username
Email
Password
Password(2)
At the moment, it is showing
Username
Password
Password (2)
Email
I am trying to follow this tutorial https://www.youtube.com/watch?v=q4jPR-M0TAQ.
I have looked at the creators notes on Github but that has not helped.
I have double checked my code and cannot see any daft typos.
Can anyone provide any insight?
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
from django.shortcuts import render, redirect
from django.contrib import messages
from .forms import UserRegisterForm
def register(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
messages.success(request, f'Account created for {username}!')
return redirect ('blog-home')
else:
form = UserRegisterForm()
return render(request, 'users/register.html', {'form':form})
{% extends "blog/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Join Today</legend>
{{ form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Sign Up</button>
</div>
</form>
<div class="border-top pt-3">
<small class="text-muted">
Already Have An Account? <a class="ml-2" href="#">Sign In</a>
</small>
</div>
</div>
{% endblock content %}
you can customize the look and order of the form by this method, create a new template in the account/ template directory, name it register.html, and make it look as follows:
{% extends "base.html" %}
{% block title %}Create an account{% endblock %}
{% block content %}
<h1>Create an account</h1>
<p>Please, sign up using the following form:</p>
<form action="." method="post">{% csrf_token %}
{{ form.username }}
{{ form.other_fields_as_you_like }}
<p><input type="submit" value="Create my account"></p>
</form>
{% endblock %}

Login, 2 views, 1 template - DJANGO

I have a homepage and in this homepage I include my connexion.html that I connect. But I have this error :
'str' object has no attribute 'visible_fields'
my homepage HTML :
{% extends "base.html" %} /* There are a css link of Bootstrap :bootstrap.min.css
<form method="POST" action="{% url 'connexion' %}" >
{% csrf_token %}
{{ form|bootstrap }}
<input type="submit" class="btn btn-success" value="Je m'inscris" >
</form>
...
<div class="panel-body">
{% load bootstrap %}
{% include "monsite/connexion.html" %}
</div>
...
My connexion.html :
<link rel="stylesheet" href="/static/css/bootstrap.min.css"/>
{% load bootstrap %,=
<form method="POST" action="{% url 'connexion' %}" >
{% csrf_token %}
{{ form|bootstrap }}
<input type="submit" class="btn btn-success" value="Login" >
</form>
My view of connexion : I have also home view
def connexion(request):
error = False
if request.method == "POST":
form = connexionForm(request.POST)
if form.is_valid():
pseudo = form.cleaned_data["pseudo"]
mdp = form.cleaned_data["mdp"]
user = authenticate(username=pseudo, password=mdp)
if user != None :
login(request,user)
return redirect(reverse(accueil))
else :
error = True
else :
form = connexionForm()
return render(request,"monsite/connexion.html",locals())
connexionForm is just a forms with 2 fields in forms.py
So I would like to login from my homepage...
Views don't work like that.
You can't include a template and expect it to somehow call a view. A template doesn't have its own view, and templates generally don't know or care which views they're called from. Including "connexion.html" just renders it with the current template context, and in this case that doesn't have any variable named "form".
If you want to include a template with a custom context, you need to use an inclusion template tag.
In locals(), there are form and all variables;
The error is in bootstrap|form in connexion.html but I dont know where