How to arrange forms fields vertically? [duplicate] - django

This question already has answers here:
How to change form layouts in Django 1.8
(6 answers)
Closed last year.
I am creating a login form by using the Forms class. Unfortunately, when I run the page I found the arrangement of the fields is horizontal. Can you help me to make it vertically, please?
In the bellow the forms.py code:
from django import forms
class LoginForm(forms.Form):
username = forms.CharField(label='Your name', max_length = 50)
password = forms.CharField(max_length = 50, widget=forms.PasswordInput)
And here is the views.py code:
from django.shortcuts import render
from .models import Login
from .forms import LoginForm
# Create your views here.
def login_function(request):
try:
username = request.POST.get('username')
password = request.POST.get('password')
data = Login(username = username, password = password)
data.save()
except:
x = 'error'
return render(request,'pages/login.html', {'loginform':LoginForm})
And here is login.html code:
{% block content %}
<form method="POST">
{% csrf_token %}
{{loginform}}
<input type="submit" value="Save">
</form>
{% endblock content %}

First Way using as_p
{% block content %}
<form method="POST">
{% csrf_token %}
{{loginform.as_p}}
<input type="submit" value="Save">
</form>
{% endblock content %}
Second Way using loop
If you want to add any additional styles to your form, then
{% block content %}
<form method="POST">
{% csrf_token %}
{% for field in loginform%}
<div class="fieldWrapper">
{{ field.errors }}
{{ field.label_tag }} <br/>
{{ field }}
</div>
{% endfor %}
<button type="submit">Save</button>
</form>
{% endblock %}
Third-way using table
{% block content %}
<form method="POST">
{% csrf_token %}
<table>
{{ loginform.as_table }}
</table>
<button type="submit">Save</button>
</form>
{% endblock %}

Related

My form does not save using bootstrap for styling in django

hello thank you for your visiting
I'm a new learner of Django
I would like to know how to style form using django-bootstrap-v5
i try this and does not work
i have this form.py
pathesForm = inlineformset_factory(
Book,
quotation,
fields=('name','time',),
can_delete=False,extra=4,max_num=4,
widgets={'name': forms.TextInput(attrs={
'placeholder': 'name of book',
})
}
)
i use django-bootstrap-v5 and in file html
this form is not working with me
<form role="form" class="form-horizontal" method="post">
{% csrf_token %}
{{ formset.management_form }}
{% for form in formset %}
<div class="row">
<div class="col-md-6">
{% bootstrap_field form.name %}
</div>
<div class="col-md-6">
{% bootstrap_field form.time %}
</div>
</div>
{% if form.maybemissing %}
{% bootstrap_field form.maybemissing %}
{% endif %}
{% endfor %}
<button type="submit">Save</button>
</form>
but this is working with me (i can save the form)
{% bootstrap_formset_errors formset %}
<form role="form" class="form-horizontal" method="post">
{% csrf_token %}
{% bootstrap_formset formset %}
<button type="submit">Save</button>
</form>
this is my view.py
def hello(request,id):
book=Book.objects.get(id=id)
if request.method == 'POST':
form= pathesForm(request.POST,request.FILES,instance=book)
if form.is_valid():
form.save()
form = pathesForm(instance=book )
return render(request,'hello/pathesForm.html',{'formset':form})
i use print('hello) to try know where is the problem and the result seems like the form is not valid
how i can to customize the style of my form like the first one
in your views you forgot to pass then else statement so here it is
def hello(request,id):
book=Book.objects.get(id=id)
if request.method == 'POST':
form= pathesForm(request.POST,request.FILES,instance=book)
if form.is_valid():
form.save()
else:
form = pathesForm(instance=book)
return render(request,'hello/pathesForm.html',{'formset':form})
and in your html while requsting the file field
you have to give form a encryptio type here it is
<form role="form" class="form-horizontal" method="POST" enctype="multipart/form-data">
this has to solve your problem and tell me if you still getting any error have a good day
allways if you have a problem with from use print(form.errors) before the form is valid and after it
i got my problem and i got this error [{'id': ['This field is required.']}
soulition:
<form role="form" method="post">
{% csrf_token %}
{{ formset.management_form }}
{% for form in formset %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
<div class="row">
<div class="col-md-6">
{% bootstrap_field form.name %}
</div>
</div>
{% if form.maybemissing %}
{% bootstrap_field form.maybemissing %}
{% endif %}
{% endfor %}
i think it success using formset only because of ( id add automatically )
and if you want to forloop you should be add it manually

How to show django form in django template?

I am trying to create a form using django and css.
views.py
from django.shortcuts import render
from .forms import ContactForm
def home(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
pass
else:
form = ContactForm()
return render(request, 'home.html', {'form':form})
forms.py
from django import forms
class ContactForm(forms.Form):
name = forms.CharField(max_length = 30)
email = forms.EmailField(max_length = 254)
message = forms.CharField(max_length = 2000, widget = forms.Textarea(),help_text = "Write Your Message here")
def clean(self):
cleaned_data = super(ContactForm, self).clean()
name = cleaned_data.get('name')
email = cleaned_data.get('email')
message = cleaned_data.get('message')
if not name and not email and not message:
raise forms.ValidationError('You have to write something!')
When I try to add the form to my html page like the following it doesn't show up. Just the button shows up, no form fields -
{% extends 'store/main.html' %}
{% load static %}
{% block content %}
<h3>Store</h3>
<form method = "post" novalidate>
{% csrf_token %}
{{ form }}
<button type='submit'>Submit</button>
</form>
{% endblock content %}
If I do css form instead it obviously show up the way it should.
{% extends 'store/main.html' %}
{% load static %}
{% block content %}
<h3>Store</h3>
<form>
<label for="fname">First Name</label>
<input type="text" id="fname" name="fname">
<button type='submit'>Submit</button>
</form>
{% endblock content %}
So I decided to add the form fields individually to the css form. Where does the {{form.name}} or {{form.email}} tag go?
EDIT:
Hey Vivek, the contact form code is this -
class ContactForm(forms.Form):
name = forms.CharField(max_length = 30)
email = forms.EmailField(max_length = 254)
message = forms.CharField(max_length = 2000, widget = forms.Textarea(),help_text = "Write Your Message here")
The html template looks like this-
{% extends 'store/main.html' %}
{% load static %}
{% block content %}
<h3>Store</h3>
<form method = "post" novalidate>
{% csrf_token %}
<label class="float-left" for="name">Name</label>
{{ form.name }}
<button type='submit'>Submit</button>
</form>
{% endblock content %}
Thanks for any input.
Accessing form fields individually will make you to render the form errors individually as well. {{form}} encapsulates everything:- Form fields , errors, non_field_errors..So if you have to access the fields individually do not forget to add the form errors.
I have written a sample code which will server the purpose.
{% csrf_token %}
{% if form.errors %}
<div class="alert alert-danger" style="text-align:left">
<ul>
{% for field in form %}
{% for error in field.errors %}
<li><strong>{{ error|escape }}</strong></li>
{% endfor %}
{% endfor %}
{% for error in form.non_field_errors %}
<li><strong>{{ error|escape }}</strong></li>
{% endfor %}
</ul>
</div>
{% endif %}
<div class="form-row">
<div class="col-md-4 mb-3">
<label class="float-left" for="id_name">Name</label>
{{ form.name }}
</div>
<div class="col-md-8 mb-3">
<label class="float-left" for="id_email">Email ID</label>
{{ form.email }}
</div>
</div>
<br>
<input type="submit" class="btn btn-primary" value="Pay" id="submit">
</form>

Any efficient way to avoiding two forloops in django

Any better or efficient way to this in django
{% for list1item in list1 %}
{% for list2item in list2 %}
{% if forloop.counter == forloop.parentloop.counter %}
{{ list1item }} {{ list2item }}
{% endif %}
{% endfor %}
{% endfor %}
I want to do something like this, but not working.
{% for list1item in list1 %}
{% with forloop.counter as i %}
{{ list2.i }}
{% endwith %}
{% endfor %}
Updated! Actually here is the story!
this is my forms.py
from django import forms
from .models import MedicalRecords
class UpdateMedicalRecordForm(forms.ModelForm):
class Meta:
model = MedicalRecords
fields = ("title", "file", "doctor")
widgets = {
"title": forms.Textarea(attrs={"rows": "", "class": "form-control"}),
}
I want a list of each medicalrecord form with It's instance so I'm using [UpdateMedicalRecordForm(instance=x) for x in medicalrecords] to create form for each medicalrecord.
my view.py is as
...
medicalrecords = get_list_or_404(MedicalRecords,somefilterings..)
forms = [UpdateMedicalRecordForm(instance=x) for x in medicalrecords]
...
then in template to access each form of medical record I'm using
<form method="POST" enctype="" class="">
<div class="modal-body">
<div class="form-group">
{% csrf_token %}
{% for form in forms reversed %}
{% if forloop.counter == forloop.parentloop.counter %}
{{ form.as_p }}
{% endif %}
{% endfor %}
</div>
<div class="submit-section text-center">
<button type="submit" class="btn btn-primary submit-btn">Submit</button>
<button type="button" class="btn btn-secondary submit-btn" data-dismiss="modal">Cancel</button>
</div>
</div>
</form>
Actually you can create a custom template tag in order to make your solution working :
# templatetags/custom_tags.py
from django import template
register = template.Library()
#register.filter
def get_index(obj, index):
"""
Try to get value from a list object with an index given in parameter.
Return an empty string if index doesn't exist
"""
try:
return obj[index]
except IndexError:
return ""
Then in your template you can do :
{% load custom_tags %}
{% for list1item in list1 %}
{{ list2|get_index:forloop.counter }}
{% endfor %}
But after reading your update, I believe you can find something cleaner for your use case.

Html code for showing multiple forms on one page

Below is the view
def TestPageView(request):
if request.method == 'POST':
contactform = ContactForm(request.POST,prefix="contact")
subscriptionform = SubscriptionForm(request.POST,prefix="subscription")
suggestionform = SuggestionForm(request.POST,prefix="suggestion")
globalmessageform = GlobalMessageForm(request.POST,prefix="globalmessage")
if contactform.is_valid() and subscriptionform.is_valid() and suggestionform.is_valid() and globalmessageform.is_valid():
contact = contactform.save()
subscription = subscriptionform.save()
suggestion = suggestionform.save()
globalmessage = globalmessageform.save()
else:
print(form.errors)
else:
contactform = ContactForm(prefix="contact")
subscriptionform = SubscriptionForm(prefix="subscription")
suggestionform = SuggestionForm(prefix="suggestion")
globalmessageform = GlobalMessageForm(prefix="globalmessage")
return render(request,'dashboard/test_page.html',{'contactform':contactform,'subscriptionform':subscriptionform,'suggestionform':suggestionform,'globalmessageform':globalmessageform})
How to write html code to show and save these forms on test_page.html.I know how to show one form but there are 4 forms in this case.
I have coded like this but i cannot see any output on test_page.html. Page is completely blank.
{% extends "base.html" %}
{% block content %}
{% load static %}
<div>
<div>
<form method="post" >
{% csrf_token %}
{{ contactform.as_p }}
</form>
</div>
<div>
<form method="post" >
{% csrf_token %}
{{ subscriptionform.as_p }}
</form>
</div>
<div>
<form method="post" >
{% csrf_token %}
{{ suggestionform.as_p }}
</form>
</div>
<div>
<form method="post" >
{% csrf_token %}
{{ globalmessageform.as_p }}
</form>
</div>
<input type="submit" name="Save">
</div>
{% endblock %}

Why is my Update URL link kicking me to the CreateNew html view

so this is a tag on from my previous stackoverflow post:
Django updateView saving another instance instead of updating
and i think i've narrowed it down. Whats happening is that when i click on the link to update my view, it sends me to the "create new" page. my problem is that I cant figure out why its doing that.
Any and all help is appreciated.
here is the code:
question_form.html
{% extends "base.html" %}
{% load bootstrap3 %}
{% block content %}
<h4>Create New Question</h4>
<form method="POST" action="{% url 'questions:create' %}" id="questionForm">
{% csrf_token %}
{% bootstrap_form form %}
<input type="submit" value="Post" class="btn btn-primary btn-large">
</form>
{% endblock %}
question_update.html
{% extends "base.html" %}
{% load bootstrap3 %}
{% block content %}
<h4>Update Question</h4>
<form method="POST" action="{% url 'questions:update' pk=question.pk %}" id="questionForm">
{% csrf_token %}
{% bootstrap_form form %}
<input type="submit" value="Update" class="btn btn-primary btn-large">
</form>
{% endblock %}
question_detail.html
{% block content %}
this is the question detail view
<h3>{{ question.question_html|safe }}</h3>
<h3>{{ question.answer_html|safe }}</h3>
Update Question
{% endblock %}
urls.py
url(r'new/$', views.CreateQuestion.as_view(), name='create'),
url(r'questionupdate/(?P<pk>\d+)/$', views.QuestionUpdate.as_view(), name='update'),
url(r'questiondetail/(?P<pk>\d+)/$', views.QuestionDetail.as_view(), name='single'),
views.py
class CreateQuestion(generic.CreateView):
model = models.Question
form = QuestionForm
fields = ('question', 'answer')
success_url = reverse_lazy('questions:all')
def form_valid(self, form):
self.object = form.save(commit=False)
self.object.user = self.request.user
self.object.save()
return super().form_valid(form)
class QuestionDetail(generic.DetailView):
model = models.Question
class QuestionUpdate(generic.UpdateView):
model = models.Question
form_class = QuestionForm
context_object_name = 'question'
From your urls.py the name of update view is only update. You can try only update tag in html file Like
{% extends "base.html" %}
{% load bootstrap3 %}
{% block content %}
<h4>Update Question</h4>
<form method="POST" action="{% url 'update' pk=question.pk %}" id="questionForm">
{% csrf_token %}
{% bootstrap_form form %}
<input type="submit" value="Update" class="btn btn-primary btn-large">
</form>
{% endblock %}
I've figured it out. it turns out I was missing the template name part under my Create and update views which directs them to their own html templates:
class CreateQuestion(generic.CreateView):
model = models.Question
form_class = QuestionForm
fields = ('question', 'answer')
template_name = "questions/question_form_create.html"
success_url = reverse_lazy('questions:all')
class QuestionUpdate(generic.UpdateView):
model = models.Question
form_class = QuestionForm
template_name = "questions/question_form_update.html"