can't raise ValidationError django validators - django

I need to know how I raise ValidationError of a validators in django.
First I tried the methode on form in simple page and forms and it works perfectly.
but the problems appear when I use modal fade class in a page works with pk
for example(127.0.0.1:8000/wsheets/AMA2/).
the message is
(The view Home.views.wellsets didn't return an HttpResponse object. It returned None instead.)
and mt views.wellsets is
def wellsets(request, WeelN):
serchedWl = WellSheets.objects.filter(WellID__exact=WeelN)
form= WelshetForm()
context ={
'title': 'SearchWS',
'Wellslistsh':serchedWl,
'WeelN':WeelN,
'form':form,
}
if request.method == 'POST':
form =WelshetForm(request.POST, request.FILES)
if form.is_valid():
form.instance.author = request.user
form.save()
return redirect('WellSheetg', WeelN)
else:
return render(request,'Home/WELLINFO/W_TchD/wellshts.html', context)
and my form + validator is:
from django.core.exceptions import ValidationError
class WelshetForm(forms.ModelForm):
WellID = forms.CharField(label='Well Name',max_length=15)
FileNm = forms.CharField(label='File Name',max_length=15)
def clean_SHRPath(self):
SHRPath = self.cleaned_data.get('SHRPath')
size= SHRPath._size
if SHRPath._size > 1024*1024*10:
raise forms.ValidationError('Size is bigger than allowed')
return SHRPath
and at last this is my html form
<button type="button" class="btn button1 btn-outline-success mb-2 btn-block" data-toggle="modal" data-target="#myModal" >
<p class="thicker">Add new Well-Sheet</p></button>
<div class="modal fade" id="myModal" role="dialog" >
<div class="modal-dialog ">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title"><p class="thicker">Upload Well-sheet</p></h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<p class="thicker">Check your file before uploading ({{WeelN}})</p>
<div class="w3-panel w3-light-grey w3-round-large solid"">
<form method="POST" id="formOne" enctype= multipart/form-data>
{% csrf_token %}
<div class="form-row">
<div class="form-group col-md-6 mb-0">
{{ form.WellID|as_crispy_field }} </div></div>
<div class="form-row">
<div class="form-group col-md-8 mb-0">
{{ form.SHRPath }}</div></div>
<p style="color:red;">Maximum upload size is 10Mb</p>
<br>
<input class="btn btn-success mb-6" name="form_uplod" type="submit" value="AddSheet">
</form>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button></div>
</div>
</div>
Modal form

As #IainShelvington said, you need to remove else block to get a response. You can try like this:
def wellsets(request, WeelN):
serchedWl = WellSheets.objects.filter(WellID__exact=WeelN)
form= WelshetForm()
if request.method == 'POST':
form =WelshetForm(request.POST, request.FILES)
if form.is_valid():
form.instance.author = request.user
form.save()
return redirect('WellSheetg', WeelN)
context ={
'title': 'SearchWS',
'Wellslistsh':serchedWl,
'WeelN':WeelN,
'form':form,
}
return render(request,'Home/WELLINFO/W_TchD/wellshts.html', context)
So that, even if the validation fails, you will get a response with form containing error data. To show form errors in template, try like this:
<div class="form-group col-md-8 mb-0">
{{ form.SHRPath }}</div>
{% if form.SHRPath.errors|length > 0 %}
<p style="color:red;">{{ form.SHRPath.errors.0 }}</p>
<br>
{% endfor %}
More information can be found in documenation.

Hi In fact I did it by other way
no error message appear in the bootstrap modal at the moment of submitting but it works fine.
in my views.py I created a new form (form_error):
def wellsets(request, WeelN):
serchedWl = WellSheets.objects.filter(WellID__exact=WeelN)
form= WelshetForm()
form_error = False
if request.method == 'POST':
form =WelshetForm(request.POST, request.FILES)
if form.is_valid():
form.instance.author = request.user
form.save()
return redirect('WellSheetg', WeelN)
else:
form_error = 'Check your file Name, type and size <10Mb'
context ={
'title': 'SearchWS',
'Wellslistsh':serchedWl,
'WeelN':WeelN,
'form':form,
'form_error': form_error,
}
return render(request,'Home/WELLINFO/W_TchD/wellshts.html', context)
and in my Html :
{% if form %}
<div class="w3-panel w3-light-grey w3-round-large solid"">
<form method="POST" id="formOne" enctype= multipart/form-data>
{% csrf_token %}
<div class="form-row">
<div class="form-group col-md-6 mb-0">
{{ form.WellID|as_crispy_field }}</div></div>
{% if form_error %}
<li style="color:red;"><strong>Check the Well if it does exist</strong></li>
{% endif %}
<div class="form-row">
<div class="form-group col-md-6 mb-0">
{{ form.FileNm|as_crispy_field }}</div></div>
<div class="form-row">
<div class="form-group col-md-6 mb-0">
{{ form.Folio|as_crispy_field }}</div></div>
<div class="form-row">
<div class="form-group col-md-8 mb-0">
{{ form.SHRPath }}</div></div>
{% if form_error %}
<li style="color:red;"><strong>{{form_error}}</strong></li>
<li style="color:red;"><strong>File type (pdf, jpg ,xls..) only accepted</strong></li>
{% endif %}
<p style="color:red;">Maximum upload size is 10Mb</p>
<br>
<input class="btn btn-success mb-6" data-target="#myModal" name="form_uplod" type="submit" value="AddSheet">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</form>
{% endif %}
and I creted a validators.py and in it:
def validate_file_size(value):
filesize= value.size
print('very nice',filesize/(1024*1024))
if filesize > 1024*1024*10:
raise ValidationError(_("The maximum file size that can be uploaded is 10MB"), code='invalid')
return value
def validate_text(value):
from Home.models import Wellinfo
WELDATA= Wellinfo.objects.filter(WellID=value)
print(value, WELDATA)
if Wellinfo.objects.filter(WellID=value).exists():
return value
raise ValidationError("The Well does't exists!")
and at last in the model.py i called the decorator as;
class WellSheets(models.Model):
WellID = models.CharField(max_length=15, validators= [validate_text])
FileNm = models.CharField(max_length=15)
Folio = models.PositiveIntegerField(blank=True, null=True)
SHRPath = models.FileField(upload_to='Well_sheets/', validators= [validate_file_size])
at the end the file will not added or uploaded and when I cambak to my modal window I see that
Description of modal window

Related

passing instance to Django modal form

I want to do edit on a modal pop up form, edit is working but cant see the existing instance, how I can do it? any help is appreciated.
Here I have passed the form as below
class DomainListView(ListView):
model = Domain
template_name = 'super_admin/domain_list.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
form = DomainEditForm(self.request.POST or None)
context['form'] = form
return context
and the template is as follows
<div class="modal fade" id="domain-edit-{{ item.pk }}">
<div class="modal-dialog" role="document">
<form class="form-valide" action="{% url 'domain_edit' item.pk %}" method="POST" id=""
enctype="multipart/form-data">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title"> Edit Domain </h5>
<button type="button" class="close" data-dismiss="modal"><span>×</span>
</button>
</div>
<div class="modal-body">
<div class="basic-form">
<div class="form-group">
{% csrf_token %}
{{ form.errors }}
{{ form | crispy }}
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">submit</button>
</div>
</div>
</form>
</div>
</div>
this is inside for loop along with list items, I tried to fetch the instance as follows in get context data override, but it gives key error
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
obj = get_object_or_404(Domain, kwargs={'pk': self.kwargs['pk']})
form = DomainEditForm(self.request.POST or None, instance=obj)
context['form'] = form
return context

Django CSRF token missing or incorrect but CSFR has been added

Django give me the following error CSRF token missing or incorrect. but I don't find the issue.
I have created my forms:
class ModCollaboratoriForm(forms.ModelForm):
class Meta:
model = AltriCosti
fields = "__all__"
and my simple views.py:
def collaboratori_commessa(request):
collaboratori_commessa=AltriCosti.objects.all()
if request.method == 'POST':
form = ModCollaboratoriForm(request.POST)
if form.is_valid():
print("Il form è valido")
new_input = form.save()
else :
form = ModCollaboratoriForm()
context={
'form':form,
'collaboratori_commessa': collaboratori_commessa,
}
return render(request, 'commesse/collaboratori_commessa.html', context)
And in my collaboratori_commessa.htm the following form:
<form id="contact-form" name="contact-form" method="post" >
{% csrf_token %}
<div class="card card-outline card-info shadow ">
<div class="card-header ">
<h4 class="mb-0">
<img src="{% static 'icon/plus-circle.svg' %}"> Informazioni generali
</h4>
</div>
<div class="card-body">
{{ form.media }}
<div class="row">
<div class="form-group col-2 0 mb-0" >
{{form.codice_commessa|as_crispy_field}}
</div>
.....
</div>
<div class="card-footer">
<div class="col-md-2">
<button class="btn btn-info form-control" type="submit" onclick="submitForm()">Registra</button>
</div>
</div>
</form>
Why django give me the CSRF Error?

Form Validation Not Displaying on Form

I have a custom form validation that runs on my popup window form. If the form validation occurs i get a bad request error which is what i have programmed in my views.py . How do i render it so the user stays on the form and the validation message displays. Thanks for the help. Here is my code.
#login_required
def K8_Points_Classroom(request):
#context_from_k8_points = request.session['k8_points_context']
if request.method == 'POST':
form = K8Points_ClassroomForm(request.POST)
if form.is_valid():
form.save(commit=False)
form.save()
class_name = form.cleaned_data.get('class_name')
getstudents = Student.objects.filter(class_name = class_name)
students = getstudents.all()
form = K8Points_ClassroomForm()
context = {'form': form ,'students' : students, 'class_name': class_name,}
return render(request,'points/k8_points_classroom.html', context)
else:
return HttpResponseBadRequest("Bad Request")
else:
return render(request, 'points/k8_points_classroom.html', {'form': form} )
Updated form.html
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% crispy K8Points_ClassroomForm %}
{% load static %}
{% block content %}
<br>
<h2>{% load static %}
<img src="{% static 'forms/star.png' %}" alt="chain" height="62" width="62"> {{class_name}}</h2>
<br>
<br>
<form action="/points/k8_points_classroom" method="POST">
{% csrf_token %}
<!-- Start Date -->
<div class="container">
<div class="container">
<div class='row'>
<div class="col-4">
<p> Recording Data as User : {{user.username}} </p>
</div>
</div>
<div class='row'>
<div class = "col-2">
{{form.date|as_crispy_field }}
</div>
<div class = "col-2">
{{form.week_of|as_crispy_field }}
</div>
<div class = "col-2">
{{form.day|as_crispy_field }}
</div>
</div>
</div>
</form>
<div class="jumbotron" align="middle">
<img src="{% static 'forms/levelup.png' %}" alt="levelup" height="120" width= "120">
<h1>My Students</h1>
<!-- Line Break -->
<hr style="border: 1px solid black;"/>
<!-- Line Break -->
<div class="row mb-3">
{% for i in students%}
<div class="col-md-4 themed-grid-col"><h2>{{i.student_name}}</h2>
<p align="left"> Today's Score: {{total}}</p>
<h4>
<button type="button" class="btn btn-primary btn-lg btn-block" data-toggle="modal"
data-target="#PointsBox{{ student.pk }}">Level Up
</button>
</h4>
<div id="PointsBox{{ student.pk }}" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<img src="{% static 'forms/star.png' %}" align="left" alt="chain" height="42"
width="42">
<h4 class="modal-title">Points Confirmation </h4>
<button type="button" class="close" data-dismiss="modal"> ×</button>
</div>
<div class="modal-body">
<h6>
<div class="modal-body">Please add the selected points for the current
student.</div>
</h6>
<form action="/points/k8_points_classroom" method="POST">
{% csrf_token %}
<div class="form-row" align='left'>
<div class="col-7">
{{form.class_name|as_crispy_field }}
<input type="student_name" class="form-control" value ="{{i}}" >
{{form.time_frame|as_crispy_field }}
</div>
</div>
<div class="form-row">
<div class="col-3" align='left'>
{{form.behavior|as_crispy_field }}
{{form.academic|as_crispy_field }}
<button type="submit" class="btn btn-success" ><i
class="fas fa-star"></i> Level Up
</button>
</div>
</div>
</div>
<div class="modal-foot"></div>
</div>
</div>
</div>
</div>
</form>
{% endfor %}
{% endblock %}
You can't return a bad response if the form is invalid. Instead, render the page again with the invalid form and in the temolate you will be able to render the errors. Try starting rendering the form just using {{ form.as_p }} and you will see the errors. The form errors are in form.errors and each field has its own errors, you can access to them form.field.erorrs
if request.method == 'POST':
form = K8Points_ClassroomForm(request.POST)
if form.is_valid():
form.save(commit=False)
form.save()
class_name = form.cleaned_data.get('class_name')
getstudents = Student.objects.filter(class_name = class_name)
students = getstudents.all()
form = K8Points_ClassroomForm()
context = {'form': form ,'students' : students, 'class_name': class_name,}
return render(request,'points/k8_points_classroom.html', context)
return render(request, 'points/k8_points_classroom.html', {'form': form} )

Django modelformset_factory deleting objects marked by can_delete

Hello I have got question I have made modelformset_factory and in options I have choosen can_delete = True and now I don't know how to delete marked objects as 'DELETE' : True to delete them from database. I was trying to do this in some ways and it didnt work. I was looking for it also in django formsetmodels documentation but this didnt help me. With this option can_delete = True I get additional checkbox in my html page Delete and marking him only prints me in console on print:
{'username': 'sw', 'email': 'a#gmail.com', 'city': 'ss', 'code': 12345, 'id': , 'DELETE': False}
Saving forms to database is working but I dont know how to delete marked forms from database.
I would be very thankful for every help.
I have made modelformset_factory from model in models.py
class TestModel(models.Model):
username = models.CharField(max_length=120)
email = models.EmailField()
city = models.CharField(max_length=120)
code = models.IntegerField()
#W admin panelu za miast TestModel object bedzie username
def __str__(self):
return self.username
Then I have added in my views.py function:
def django_modelformset(request):
TestModelFormset = modelformset_factory(TestModel, fields=['username', 'email', "city",
"code"], extra=1, can_delete=True)
formset = TestModelFormset(request.POST or None)
if formset.is_valid():
for form in formset:
print(form)
print(form.cleaned_data)
form.save()
context = {"formset": formset}
return render(request, "modelformset.html", context)
My modelformset.html looks like this:
<form method="POST" action="">
{% csrf_token %}
{{ formset.management_form}}
{% for form in formset %}
<div>
{{ form.as_p }}
<hr/>
</div>
{% endfor %}
<input type="submit" value="Save">
I haven't personally had to do this, but from the docs it seems you have a few options.
Call save on the formset instead of each form.
if formset.is_valid():
formset.save()
If you must loop through each form you could something like this.
if formset.is_valid():
for form in formset:
print(form.cleaned_data)
if form.cleaned_data["DELETE"]:
# Do what you want with the form data
# i.e. get the object from the database and delete it.
else:
form.save()
Loop through the deleted forms separately.
if formset.is_valid():
forms = formset.save(commit=False)
for object in formset.deleted_objects:
object.delete()
It's work for me
view.py
Blog_MetaFormSet = modelformset_factory(Metas, form=MetaForm, extra=0, can_delete=True)
Blog_MetaQuerySet = Metas.objects.filter(blog=blog_obj).order_by('created_at')
contex={
"blog_meta_formset": Blog_MetaFormSet(request.POST,queryset=Blog_MetaQuerySet),
}
if blog_meta_formset.is_valid():
for metaform in blog_meta_formset:
meta_obj = metaform.save(commit=False)
meta_obj.blog = blog_obj
if metaform.cleaned_data["DELETE"]==True:
meta_obj.delete()
else:
meta_obj.save()
In Templates
<div class="row">
<div id="cfield-form-list"> {{ blog_meta_formset.management_form }} {% for meta_form in blog_meta_formset %}
<div id="form-{{forloop.counter0}}" class="cfield-form xrow">
<div class="col-md-12 mb-3">
<div class="row d-flex align-items-center">
<div class="col-md-4">
<label class="form-label">Name</label> {{ meta_form.title|attr:"class:form-control"|attr:"type:text" }} </div>
<div class="col-md-4">
<label class="form-label">Value</label> {{ meta_form.value|attr:"class:form-control"|attr:"rows:2" }} </div>
<div class="col-md-4">
<div class="form-check custom-checkbox mb-3 checkbox-primary"> {{ meta_form.DELETE|attr:"class:form-check-input"|attr:"type:checkbox" }}
<label class="form-check-label" for="customCheckBox2">Delete</label>
</div>
</div>
</div>
</div> {{meta_form.id}} </div> {% endfor %} </div>
<div id="empty_form" class="hidden">
<div class="col-md-12 mb-3">
<div class="row d-flex align-items-center">
<div class="col-md-4">
<label class="form-label">Name</label> {{ blog_meta_formset.empty_form.title|attr:"type:text"|attr:"class:form-control" }} </div>
<div class="col-md-4">
<label class="form-label">Value</label> {{ blog_meta_formset.empty_form.value|attr:"class:form-control"|attr:"rows:2" }} </div>
<div class="col-md-4">
<div class="form-check custom-checkbox mb-3 checkbox-primary"> {{ blog_meta_formset.empty_form.DELETE|attr:"class:form-check-input"|attr:"type:checkbox" }}
<label class="form-check-label" for="customCheckBox2">Delete</label>
</div>
</div>
<div class="col-md-4">
<button type="button" class="btn btn-danger remove_cfield" rel="">Delete</button>
</div>
</div>
</div>
</div>
<div class="col-md-12">
<button type="button" id="add-cfield" class="btn btn-primary mb-3 mt-3 ">Add Custom Field</button>
</div>
</div>
In js
const totalNewForms = document.getElementById('id_form-TOTAL_FORMS')
const addMoreBtn = document.getElementById('add-cfield')
addMoreBtn.addEventListener('click',add_new_form)
function add_new_form(event){
if (event){
event.preventDefault()
}
const currentCF_Forms = document.getElementsByClassName('cfield-form')
console.log(currentCF_Forms)
const currentCF_FormCount = currentCF_Forms.length //+ 1
const formCopyTarget = document.getElementById('cfield-form-list')
const copyEmptyFormEl = document.getElementById('empty_form').cloneNode(true)
//remove class hidden
copyEmptyFormEl.setAttribute('class','cfield-form xrow')
copyEmptyFormEl.setAttribute('id',`form-${currentCF_FormCount}`)
const regex = new RegExp('__prefix__','g')
copyEmptyFormEl.innerHTML = copyEmptyFormEl.innerHTML.replace(regex,currentCF_FormCount)
totalNewForms.setAttribute('value', currentCF_FormCount +1)
//now add new empty form element to our html form
formCopyTarget.append(copyEmptyFormEl)

Flask landing page contact form

I learn Flask and started to make a simple landing page for the project. Here is the route that handles the contact form
#app.route("/courses")
def courses():
form = ContactForm()
if request.method == 'POST':
if form.validate() == False:
flash('All fields are required.')
return render_template('courses.html', title="contact", form=form)
else:
msg = Message(recipients=['coterakg#gmail.com'])
msg.body = """From: %s <%s>%s"""%(form.name.data, form.email.data, form.message.data)
mail.send(msg)
return render_template('courses.html', title="contact", success=True)
if request.method == 'GET':
return render_template('courses.html', title="contact", form=form)
Then there is a template part which has the form
<form class="form-horizontal" action="{{ url_for('index') }}" id="contactform" method="post">
<div class="modal-header">
<h4>Задайте нам любой вопрос!</h4>
</div>
<div class="modal-body">
{{ form.hidden_tag() }}
<div class="form-group">
<label for="contact-name" class="control-label">Имя:</label>
<div>
{{ form.name }}
</div>
</div>
<div class="form-group">
<label for="contact-email" class="control-label">Email:</label>
<div>
{{ form.email }}
</div>
</div>
<div class="form-group">
<label for="question" class="control-label">Ваш вопрос:</label>
<div>
{{ form.message }}
</div>
</div>
</div>
<div class="modal-footer">
<a class="close-reveal-modal">×</a>
<button class="button" type="submit" value="contact" data-reveal-id="closeModal">Отправить</button>
<div data-reveal class="reveal-modal" id="closeModal">
<h1>Спасибо за Ваш вопрос!</h1>
<a class="close-reveal-modal">×</a>
</div>
</div>
</form>
And lastly - the part with form
from flask.ext.wtf import Form
from wtforms import StringField, BooleanField, SubmitField
from wtforms.validators import DataRequired
class ContactForm(Form):
name = StringField("Name", validators=[DataRequired()])
email = StringField("Email", validators=[DataRequired()])
message = StringField("Message", validators=[DataRequired()])
submit = SubmitField("Send")
Any ideas why this is not working?
here is a good examples for you https://github.com/jawr/flask-contact/blob/master/main.py
And detailed steps here http://code.tutsplus.com/tutorials/intro-to-flask-adding-a-contact-page--net-28982
I would also suggest you to use some 3rd party service as a mail server (Mandrill, etc).