validation error is not shown before also when i created form using form api i send error but is does not appear in html and now also when created User using UserCreationForm now also error not appered in html submitting this form without fillig single field.
views.py file
from django.shortcuts import render
from .forms import signup
# Create your views here.
def sign_up(request):
fm = signup()
if request.method == 'POST':
fm = signup(request.POST)
if fm.is_valid() :
print('until this runs')
fm.save()
else:
fm = signup()
print(fm.errors)
return render(request, 'at/signup.html', {'form': fm})
forms.py file
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class signup(UserCreationForm):
class Meta:
model=User
fields=['username','first_name','last_name','email']
html file
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
<meta charset="UTF-8">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<title>Form</title>
</head>
<body>
<div class="container" >
{{ form.non_field_errors }}
<form method="post" novalidate>
{% csrf_token %}
{{ fms.as_p }}
<button class="text-center btn btn-primary" type="submit">SUB</button>
</form>
</div>
</body>
</html>
tried this html code also but no erros are seen
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>user regisration</title>
</head>
<body>
{{ form.non_field_errors }}
{% if messages %}
<ul>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{{ form.non_field_errors }}
<form action="" method='POST' novalidate>
{% csrf_token %}
{% for fm in form %}
{{fm.label_tag}} {{fm}} {{fm.errors|striptags}} <br> <br>
{% endfor %}
<input type="submit" value='submit'>
</form>
</body>
</html>
When rendering fields manually, you are responsible for displaying the error messages.
https://docs.djangoproject.com/en/3.1/topics/forms/#rendering-form-error-messages
Related
I am making a forms page and I would like when I click the "Submit" button it renders the person on another page that I will create.
Prenotazioni.html
{% extends 'base.html' %}
{% block content %}
<br><br><br>
<div class="container" style="max-width: 600px;">
<form method='POST'> {% csrf_token %}
{{ form.as_p }}
<input type='submit' class="btn btn-warning" value='Submit'/>
</form>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.1/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.1/dist/js/bootstrap.bundle.min.js"
integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4"
crossorigin="anonymous"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
{% endblock %}
forms.py
from django import forms
from .models import Prenotazioni
class PrenotazioniForm(forms.ModelForm):
class Meta:
model = Prenotazioni
fields = [
'Nome',
'Codice_di_Sicurezza',
'Telegram',
'Livello_di_conoscenza_della_economia_da_1_a_10',
]
The more I search online, the more confused I get. Many thanks in advance!
In my code below all the questions & related images stored in my table are coming on same page at one go but I want only first question and its image to appear and than when user clicks on next button the second question along with its image should come, this should repeat till end of records in the table.
View
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from quiz.models import Quiz, Question
def playQuiz(request):
data=Question.objects.filter(__isnull=False)
res=render(request,'quiz/quiz_play.html',{'data':data})
return res
Template
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
{% for data in data %}
<div><h1> {{data.qs}} </h1></div>
<div> <img src="{{ data.qip.url }}" height=300> </div>
<input type="button" name="next-btn" value="NEXT">
{% endfor %}
</body>
</html>
You can use a Paginator to achieve this. It will automatically handle the going forward or backward.
from django.shortcuts import render
from django.core.paginator import Paginator
from quiz.models import Quiz, Question
def playQuiz(request):
data=Question.objects.filter(__isnull=False)
paginator = Paginator(data, 1) # Show 1 data per page.
page_number = request.GET.get('page')
page_obj = paginator.get_page(page_number)
res = render(request, 'quiz/quiz_play.html', {'page_obj': page_obj})
return res
In your template you will use it like this.
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
{% for data in page_obj %}
<div><h1> {{data.qs}} </h1></div>
<div> <img src="{{ data.qip.url }}" height=300> </div>
<input type="button" name="next-btn" value="NEXT">
{% endfor %}
<div class="pagination">
<span class="step-links">
{% if page_obj.has_previous %}
« first
previous
{% endif %}
<span class="current">
Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.
</span>
{% if page_obj.has_next %}
next
last »
{% endif %}
</span>
</div>
</body>
</html>
If one wanted to operate the on the "next_object" what would need to be done to the code below to allow for the objects or an id of the object to be passed back to "send_and_receive():" with a post method?
For the sake of the people who want to immediately close this as a duplicate of referencing in an insecure way, I am asking for doing this with POST not GET.
routes.py code
#app.route('/statistics', methods=['POST'])
def send_and_receive():
reference_form = ReferenceForm()
if reference_form.object_approved.data:
library.approve_object(??reference_object_id_or_object??)
return redirect('index')
if reference_form.object_rejected.data:
library.reject_object(??reference_object_id_or_object??)
return redirect('index')
next_object = library.get_next()
return render_template('site.html', reference_form=reference_form, next_object=next_object)
site.html
{% extends "base.html" %}
{% block content %}
<form action="" method="post">
<p>{{next_object.string()}}</p>
<p>{{ reference_form.object_approved() }}</p>
<p>{{ reference_form.object_rejected() }}</p>
</form>
{% endblock %}
Forms.py code
class ReferenceForm(FlaskForm):
object_approved = SubmitField("Approve")
object_rejected = SubmitField("Reject")
Make sure that you set the app's SECRET_KEY and render out the hidden fields in the html template, including the automatically added (see documentation) csrf_token hidden field.
A simple example:
app.py
from flask import Flask, render_template, flash
from flask_wtf import FlaskForm
from wtforms import SubmitField, HiddenField
class ReferenceForm(FlaskForm):
object_id = HiddenField()
object_approved = SubmitField("Approve")
object_rejected = SubmitField("Reject")
app = Flask(__name__)
app.config['SECRET_KEY'] = '123456790'
#app.route('/', methods=['GET', 'POST'])
def index():
_form = ReferenceForm()
_form.object_id.data = 42
if _form.validate_on_submit():
flash('Object ID:{}'.format(_form.object_id.data))
print(_form.object_approved.data)
print(_form.object_rejected.data)
print(_form.object_id.data)
# process form blah blah
# would be usual to return a redirect here
return render_template('index.html', reference_form=_form)
if __name__ == '__main__':
app.run()
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% with messages = get_flashed_messages() %}
{% if messages %}
<ul class=flashes>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
<form action="" method="post">
{{ reference_form.object_id() }}
{{ reference_form.csrf_token() }}
<p>{{ reference_form.object_approved() }}</p>
<p>{{ reference_form.object_rejected() }}</p>
</form>
</body>
</html>
Note how the html gets rendered, especially the two hidden fields, object_id and csrf_token:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="" method="post">
<input id="object_id" name="object_id" type="hidden" value="42">
<input id="csrf_token" name="csrf_token" type="hidden" value="IjBjNGIwNWE2NDA5NDVmZjhiMjU3Y2E5YTIwY2QwMGVlMTMxYzViYzUi.X0oupA.g9KjI79vZvfEIW1mwzR7nvHc6Yc">
<p><input id="object_approved" name="object_approved" type="submit" value="Approve"></p>
<p><input id="object_rejected" name="object_rejected" type="submit" value="Reject"></p>
</form>
</body>
</html>
I have a Django form where the person needs to add their details to subscribe and I want the page to show successful submission message below the submit button for few seconds (lets say 3) and then it should disappear and the form fields should be displayed empty.
The function definition in views.py is as follows :
def new_customer(request):
if request.method == "POST":
form = customer_form(request.POST)
if form.is_valid():
form.save()
messages.add_message(request, message_constants.SUCCESS, '✔️ SUCCESSFUL SUBSCRIPTION')
return HttpResponseRedirect('http://127.0.0.1:8000/subscribe/')
else:
form = customer_form()
return render(request,"new_customer.html",{'form':form})
The Django template :
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Subscribe</title>
<link href="https://fonts.googleapis.com/css?family=Poppins&display=swap" rel="stylesheet">
<link href="{% static "nav.css" %}" rel="stylesheet">
<link href="{% static "form.css" %}" rel="stylesheet">
</head>
{% include "navbar.html" %}
<body>
<form method="POST" class="post-form" enctype="multipart/form-data">{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="btn">Subscribe</button>
{% if messages %}
<ul id ="successMessage" class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %} style="color:green; font-size: 20px; list-style-type: none;">{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
</form>
</body>
</html>
The current code helps display the message for successful submission, as well as empty form fields but does not make it disappear.
Could anyone help ?
I suggest you use jQuery to make messages disappear and make form empty,
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
<script text="javascript">
setTimeout(fade_out, 3000);
function fade_out() {
$(".messages").fadeOut().empty();
}
$(".post-form")[0].reset(); // this is to reset the form
</script>
I am a newbie to Django. In a project I have to take inputs for multiple models in Django using forms.
For every model I have written functions (in views.py) and its corresponding Django template (in template folder).
Such as,my Add Teacher function is,
def add_teacher(request):
form = TeacherForm()
if request.method=="POST":
form = TeacherForm(request.POST)
if form.is_valid():
form.save(commit=True)
return index(request)
else:
print(form.errors)
return render(request,"billing/add_teacher.html",{"form":form})
And billing/add_teacher.html template is,
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add Teacher</title>
</head>
<body>
<h1>Add a Discipline</h1>
<div>
<form id="teacher_form" method="post" action="/billing/add_teacher/">
{% csrf_token %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% for field in form.visible_fields %}
{{ field.errors }}
{{ field.help_text }}
{{ field }}
{% endfor %}
<input type="submit" name="submit" value="Add Teacher"/>
</form>
</div>
</body>
</html>
Now, I want to use a template for all of my functions.Such as, I want to use this template for all functions with the help of Django template context processor.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{ title }}</title>
</head>
<body>
<h1>{{ h1 }}</h1>
<div>
<form id={{ form_id }} method="post" action="{{ action }}">
{% csrf_token %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% for field in form.visible_fields %}
{{ field.errors }}
{{ field.help_text }}
{{ field }}
{% endfor %}
<input type="submit" name="submit" value={{ value }}/>
</form>
</div>
</body>
</html>
But when I return render() function I only can set either context or form.Such as, I can use one of these,
return render(request,"billing/add_teacher.html",{"form":form})
or,
return render(request,"billing/add_teacher.html",context= context_dict)
How can I use both of these together?
Something like,
return render(request,"billing/add_teacher.html",{"form":form},context =context_dict)
Thank you.
Try the following
context_dict.update({"form":form})
return render(request, "billing/add_teacher.html", context=context_dict)