Django form field doesn't appear on the template - django

I try to use Django forms but I have problems displaying all the fields on my Template.
I have created a form in the form.py file as:
class UploadCSVForm(forms.Form):
title = forms.CharField(max_length=255, help_text="Please type here", required=True)
csv_load = forms.FileField()
In my corresponding view I import the form as:
from myproject.myapp.forms import UploadCSVForm
and then in the specific view function I render the form as;
if request.method == 'GET':
....
....
form = UploadCSVForm()
ctx['form'] = form
return render_to_response(template, RequestContext(request, ctx))
Last in my template I call the form as:
<form id="file-uploader" method="post" enctype="multipart/form-data" action="{% url "layer" %}">
<input type="hidden" name="csrfmiddlewaretoken" value="{{ csrf_token }}">
{% for field in form.visible_fields %}
{{ field.errors }}
{{ field.help_text }}
{{ field }}
{% endfor %}
<button type="submit" id="upload-button" class="btn btn-danger">Upload</button>
</form>
I only get to see the csv_load but not the title.
What am I doing wrong here?

Related

Unable to see error messages in registration template. Django

Good afternoon Community,
I hope you are all well.
I am building my first website and I have the following problem; when I try to create a new user, if the user enters the wrong data the template does not show the error. Any hints?
Template:
<form action= "" method='post'>
{% csrf_token %}
{% for field in form %}
<p>{{field.label}}{{field}}</p>
{% endfor %}
<button type="submit" class="btn btn-success">Create User</button>
Views.py:
def register_page(request):
form = UserForm
if request.method == 'POST':
form = UserForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('http://127.0.0.1:8000/login_user/')
context = {'form' : form}
return render(request, 'simple_investing/register.htm', context)
Forms.py:
class UserForm(UserCreationForm):
class Meta:
model = User
fields = ('username', 'email', 'password1', 'password2')
As is discussed in the rendering fields manually section of the documentation, for the fields you should also render {{ field.errors }}, and the {{ form.non_field_errors }} which deals with errors not specific to one form.
The template thus should look like:
<form action= "" method="post">
{% csrf_token %}
{{ form.non_field_errors }}
{% for field in form %}
<p>
{{ field.errors }}
{{ field.label }}
{{ field }}
</p>
{% endfor %}
<button type="submit" class="btn btn-success">Create User</button>
</form>
The section also discusses how to enumerate over the errors, and apply certain styling to these errors.

pass data to form filed in django templae

How can I pass data to form fields in django templat ? , for example I have below code in my project:
<td class="col-3">
{{form.number|as_crispy_field}}
</td>
Can I use
<td class="col-3">
{{form.number}} = 10
</td>
in django template ?
#mosi -
<td class="col-3">
{{form.number}} = 10
</td>
No, you cannot use this. If you are planning to pass data from views to template then do something like this
Let's say you have a form something like this
forms.py
from django import forms
class ContactForm(forms.Form):
name = forms.CharField(max_length=30)
email = forms.EmailField(max_length=254)
views.py
def home(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
pass # your logic here
else:
form = ContactForm()
return render(request, 'home.html', {'form': form})
template.html
<form method="post" novalidate>
{% csrf_token %}
{{ form.name }}
{{form.email}}
<button type="submit">Submit</button>
</form>
OR
Simply
<form method="post" novalidate>
{% csrf_token %}
{{ form }}
<button type="submit">Submit</button>
</form>
Now, if you want to set initial values to your form in template
Lets say you have the following
class ContactForm(forms.Form):
name = forms.CharField(max_length=30,initial='test')
Then in your template you do something like this
<form method="post" novalidate>
{% csrf_token %}
<input type="text" name="name" id="name" value="{{ form.name.value }}">
<button type="submit">Submit</button>
</form>
Now, in case of an UpdateView where data is pulled in dynamically from the Database based on let's say product id. The following is just an example
class ProductForm(forms.ModelForm):
class Meta:
model = Product
exclude = (
"created_by",
"slug",
)
class ProductUpdateView(UpdateView):
# specify the model you want to use
model = Product
form_class = ProductForm
template_name = "catalog/product/update_product.html"
product_update.html
<form method="post" enctype="multipart/form-data">
<div class="card-body">
{% csrf_token %}
{{ form.as_p}}
<button type="submit" class="btn btn-primary">Update</button>
</div>
</form>
Or
<form method="post" enctype="multipart/form-data">
<div class="card-body">
{% csrf_token %}
<input type="text" name="name" id="name" value="{{ form.name.value }}">
<input type="text" name="description" id="description" value="{{ form.description.value }}">
.........
<button type="submit" class="btn btn-primary">Update</button>
</div>
</form>

django multi form and file field

I am currently using several differences forms on a single view. I am able to fill my forms but when I submit one of them, it seems that my form is invalid. I displayed the request.POST (it contains all my information) and my form (it contains my information except files parts.)
Could you explain me how to correct it?
Could it be linked to my models?
(I am using bootstrap 3 through django)
my view :
def view_addfiles(request):
try:
print(request.POST)
except:
{}
if request.method == 'POST' and 'search' in request.POST:
print("recherche")
recherche=searchbar(request.POST, prefix='search')
if recherche.is_valid():
print("recherche")
else :
recherche=searchbar(prefix='search')
if request.method == 'POST' and 'film' in request.POST:
print("film")
addfilm=Addfilms(request.POST,request.FILES, prefix='film')
print(addfilm)
if addfilm.is_valid():
print("film")
return redirect(view_accueil, inscription=3)
else :
print("dfsd")
addfilm=Addfilms(prefix='film')
if request.method == 'POST' and 'serie' in request.POST:
print("serie")
addserie=Addseries(request.POST,request.FILES, prefix='serie')
if addserie.is_valid():
print("serie")
return redirect(view_accueil, inscription=3)
else :
addserie=Addseries(prefix='serie')
return render(request, 'menuAjout.html',locals())
my html :
<form action="{% url "add_files" %}" method="post">
{% csrf_token %}
{{ recherche.as_p }}
<input type="submit" id="validation" name="search"/>
</form>
<div id="films">
{% load bootstrap3 %}
{% bootstrap_css %}
<form action="{% url "add_files" %}" method="post">
{% csrf_token %}
{% bootstrap_form addfilm %}
{% buttons %}
<button type="submit" class="btn btn-primary" id="submitbutton" name="film" value="submit">
{% bootstrap_icon "star" %} Ajouter
</button>
{% endbuttons %}
</form>
</div>
<div id="series">
<form action="{% url "add_files" %}" method="post">
{% csrf_token %}
{% bootstrap_form addserie %}
{% buttons %}
<button type="submit" class="btn btn-primary" id="submitbutton" name="serie">
{% bootstrap_icon "star" %} Ajouter
</button>
{% endbuttons %}
</form>
</div>
my forms :
class Addseries(forms.ModelForm):
class Meta:
model = series
exclude = ('nbTelechargement','datedepot')
class Addfilms(forms.ModelForm):
class Meta:
model = series
exclude = ('nbTelechargement','datedepot')
class searchbar(forms.Form):
motclef=forms.CharField(max_length=15,widget=forms.TextInput(attrs={'placeholder': 'Search...','style':'background :#ededef url("/static/image/search.png") no-repeat;background-size: auto 90%;'}))
categorie=forms.ChoiceField(choices=(('films', 'films'),
('séries', 'séries'),
('jeux', 'jeux'),
('logiciels', 'logiciels'),
('livres', 'livres'),
('musiques', 'musiques')))
I see several things:
It's not a Django issue but a HTML one:
When a user submits a form, he/she submits only form.
Django receives in request.POST only the data sent by one form.
Your forms share the same fields' names.
Addseries.nbTelechargement and Addfilms.nbTelechargement will have the same key in request.POST
I just forgot to add enctype="multipart/form-data" in my form balise.
My request.FILES was empty because of that.
So my form was unvalid because of that.

Form error doesnt display on template?

When I enter an invalid email adress I cant see an error message like "This is not an invalid email".
My comment_form.html:
{% load i18n %}
<form action="/comment/create/" method="post">
{% csrf_token %}
{{ form.errors }}
{% for field in form %}
<div class="fieldWrapper">
{{ field.label_tag }}
{{ field }}<p>
</div>
{% endfor %}
<input type="hidden" name = "object_id" value="{{object_id}}" />
<input type="hidden" name= "next" value="{{ next }}" />
<input type="submit" value="{% trans "Submit" %}">
</form>
my post_detail.html:
extends "base.html" %}
{% block content %}
<div id="exap">
{{ post.content }}
</div>
<div class="comment">
{% for comment in comments %}
<user>{{ comment.owner }}</user>
{{ comment.content}}
{% endfor %}
</div>
{% include "comment_form.html" %}
{% endblock %}
this is my comment.views
def create(request):
if request.method == 'POST':
form = CommentForm(request.POST)
email = request.POST.get('email')
next = request.POST.get('next')
if form.is_valid():
content_type = ContentType.objects.get(app_label="post", model="post")
object_id = request.POST["object_id"]
comment = Comment.objects.create(
content_type = content_type,
object_id = object_id,
content = request.POST.get('content'),
owner= request.POST.get('owner'),
email = request.POST.get('email')
)
else:
print form.errors
else:
form = CommentForm()
return HttpResponseRedirect(next)
Error message doesnt display in template ?
Where am I wrong ?
karthikr is trying to tell you what is wrong in the comments. You are not using the form to validate, so it won't show any errors. Instead of doing if validateEmail(email) you should have the email validation code inside the form class, and in the view you call if form.is_valid().
Plus, when you do write the form's clean_email method, you should not be catching ValidationError: that's the way that errors are passed on to the form's errors list.

How to display choicefield select widget on template?

This is my view:
CHOICES = (('10','10'), ('20','20'),('30','30'), ('50','50'))
class Droplist (forms.Form):
number = forms.ChoiceField(choices = CHOICES)
def page_objects(request):
if request.method == 'POST': # If the form has been submitted...
form = Droplist(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
pass #pages = form.cleaned_data['value']
#return AutoPaginateNode(paginate_by=pages) # Redirect after POST
else:
form = Droplist() # An unbound form
return render_to_response('pagination.html', {'form': form })
This is my template:
<form action="/submit/" method="post">{% csrf_token %}
{{ form }}
<input type="submit" value="Select">
</form>
how can i render my form, because i need to have a dropdown box with choices on template? what i've missed?
You need to use {{ form.as_p }}:
<form action="/submit/" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Select">
</form>
You can also use {{ form.as_table }} to output table rows but you'll need to provide your own <table> and form.as_ul to output list items:
<form action="/submit/" method="post">{% csrf_token %}
<table>
{{ form.as_table }}
</table>
<input type="submit" value="Select">
</form>
You can find more information on Displaying a form using a template on Django's documentation