Problem : I want to do the whole thing with the Form_Setting class in the forms.py file. Here I have defined the 4 submit buttons. I then use the buttons in the settings.html. In the routes.py file I want to react when they are pressed. However, at the moment it is still so that I can react with form.validate_on_submit() only generally on the submit. How can I distinguish which of the submit buttons were pressed to then perform different actions?
routes.py
from page import app
from flask import render_template, redirect, url_for
from page.models import Settings
from page.forms import Form_Setting
from page import db
#app.route('/settings', methods=['GET','POST'] )
def Settings_Page():
form = Form_Setting()
if form.validate_on_submit():
save_email = Settings(email_adress=form.email_adress.data)
db.session.add(save_email)
db.session.commit()
return redirect(url_for('Settings_Page'))
return render_template('settings.html',form=form)
forms.py
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
class Form_Setting(FlaskForm):
email_adress = StringField(label='Email')
dooralarm_time = StringField(label='Türalarm')
minimum_temp = StringField(label='MinTemp')
maximum_temp = SubmitField(label='MaxTemp')
submit_email = SubmitField(label='Eingabe')
submit_door = SubmitField(label='Eingabe')
submit_temp_max = SubmitField(label='Eingabe')
submit_temp_min = SubmitField(label='Eingabe')
settings.html
{%extends 'base.html' %}
{% block ActivSettings%}
active
{% endblock %}
{% block css %}
<link rel="stylesheet" type="text/css" href="{{url_for('static',filename='css/style.css')}}"/>
{% endblock %}
{% block title %}
Einstellungen
{% endblock %}
{% block content %}
<div>
<div class="container">
<h1 class="setting-page">Einstellungen</h1>
<!--Email Adresse-->
<div class="row ">
<div class="col-sm-12">
<div class="d-flex justify-content-start align-items-center" style="height: 8vh;">
<div class="col-sm-3 ">
<h3 class="setting-label">E-mail</h3>
</div>
<div class="col-sm-9">
<form method="POST" class="form-register flex-fill d-flex" >
<!--Schutz gegen CSRF-->
{{ form.hidden_tag() }}
{{ form.email_adress(class="form-control", placeholder="E-Mail") }}
{{ form.submit_email(class="btn btn-md btn-block btn-primary", style="background-color: #6941c6; border:none; color: #f9f5ff; margin-left: 1vw;" )}}
</form>
</div>
</div>
<hr class="divider">
</div>
</div>
<!--Türalarm Zeitintervall-->
<div class="row ">
<div class="col-sm-12">
<div class="d-flex justify-content-start align-items-center" style="height: 8vh;">
<div class="col-sm-3 ">
<h3 class="setting-label">Türalarm Zeitintervall</h3>
</div>
<div class="col-sm-9">
<form method="POST" class="form-register flex-fill d-flex" >
<!--Schutz gegen CSRF-->
{{ form.hidden_tag() }}
{{ form.dooralarm_time(class="form-control", placeholder="Zeitintervall") }}
{{ form.submit_door(class="btn btn-md btn-block btn-primary", style="background-color: #6941c6; border:none; color: #f9f5ff; margin-left: 1vw;" )}}
</form>
</div>
</div>
<hr class="divider">
</div>
</div>
<!--Temp. Schwellwert Minimal-->
<div class="row ">
<div class="col-sm-12">
<div class="d-flex justify-content-start align-items-center" style="height: 8vh;">
<div class="col-sm-3 ">
<h3 class="setting-label">Temp. Schwellwert Minimal</h3>
</div>
<div class="col-sm-9">
<form method="POST" class="form-register flex-fill d-flex" >
<!--Schutz gegen CSRF-->
{{ form.hidden_tag() }}
{{ form.dooralarm_time(class="form-control", placeholder="Temp. Minimal") }}
{{ form.submit_temp_max(class="btn btn-md btn-block btn-primary", style="background-color: #6941c6; border:none; color: #f9f5ff; margin-left: 1vw;" )}}
</form>
</div>
</div>
<hr class="divider">
</div>
</div>
<!--Temp. Schwellwert Maximal-->
<div class="row ">
<div class="col-sm-12">
<div class="d-flex justify-content-start align-items-center" style="height: 8vh;">
<div class="col-sm-3 ">
<h3 class="setting-label">Temp. Schwellwert Maximal</h3>
</div>
<div class="col-sm-9">
<form method="POST" class="form-register flex-fill d-flex" >
<!--Schutz gegen CSRF-->
{{ form.hidden_tag() }}
{{ form.dooralarm_time(class="form-control", placeholder="Temp. Maximal") }}
{{ form.submit_temp_min(class="btn btn-md btn-block btn-primary", style="background-color: #6941c6; border:none; color: #f9f5ff; margin-left: 1vw;" )}}
</form>
</div>
</div>
<hr class="divider">
</div>
</div>
</div>
</div>
{% endblock %}
Webseite
The result for the page
You can iterate through request.form using the variable name of the submit button.
from flask import request
if 'submit_email' in request.form:
# do something
elif 'submit_door' in request.form:
# do something
Be sure that the form will still validate properly form.validate_on_submit()
Related
I am creating a web page and i'm wondering if i could make sure that the data on the left is filled before pressing the blue button. On the left you can see a form to pay by entering your address, city etc. but on the right you can see another form with stripe implemented to pay with credit card. I don't know how to get the data from the left and save it in the database so I can create a receipt after successful payment. Here is the code down below.
<div class="container-2">
<div class="gray-hover">
<form method="POST">
<div class="item" id="payment">
<div class="row">
<h4>Možnost nakupa 1: Plačilo po povzetju <small><i>(Za plačevanje s kartico je treba izbrati samo
količino in vrsto izdelka!)</i></small></h4>
{% csrf_token %}
{% if form %}
<div class="input-group">
<div style="color: red;">{{ form.name.errors }}</div>
{{ form.name }}
</div>
<div class="input-group">
<div style="color: red;">{{ form.last_name.errors }}</div>
{{ form.last_name }}
</div>
<div class="input-group">
<div style="color: red;">{{ form.street_name.errors }}</div>
{{ form.street_name }}
</div>
<div class="input-group">
<div style="color: red;">{{ form.city_name.errors }}</div>
{{ form.city_name }}
</div>
<div class="input-group">
<div style="color: red;">{{ form.email.errors }}</div>
{{ form.email }}
</div>
<div class="input-group">
<div style="color: red;">{{ form.number.errors }}</div>
{{ form.number }}
</div>
{% endif %}
</div>
</div>
<div class="item" id="payment2">
<div class="row">
<div class="input-group">
{{ form.num_elements.errors }}
{{ form.num_elements }}
</div>
<div class="input-group" id="check_div">
<div
style="display: flex;width:100%;justify-content: space-between;align-items: center;font-size:medium;flex-wrap: wrap;">
<div style="display: flex;justify-content: space-between;margin:3px;">
{{ form.select_type.errors }}
{{ form.select_type.label_tag }}
{{ form.select_type }}
</div>
<div style="display: flex;justify-content: space-between;margin:3px;">
{{ form.select_type2.errors }}
{{ form.select_type2.label_tag }}
{{ form.select_type2 }}
</div>
</div>
</div>
<div class="input-group">
{{ form.warning_el.errors }}
{{ form.warning_el }}
</div>
<div style="display: flex;justify-content: space-between;margin: 0.5rem;">
<button class="button" type="submit" id="button"> Naroči <small>(povzetje)</small></button>
<a class="button" id="stripe-button">Plačaj s kartico!</a>
</div>
</div>
</div>
</form>
</div>
<div class="gray-hover">
<div class="item" id="payment3" style="width:100%;">
<h4>Možnost nakupa 2: Plačilo s kartico <small><i>(Za plačevanje s kartico je treba izbrati samo
količino in vrsto izdelka!)</i></small></h4>
<div class="row" style="display: flex; justify-content: center;">
<form id="payment-form" data-locale="si" style="width:100%;">
<div id="payment-element">
<!--Stripe.js injects the Payment Element-->
</div>
<button id="submit" class="button1">
<div class="spinner hidden" id="spinner"></div>
<span id="button-text">Plačaj</span>
</button>
<div id="payment-message" class="hidden"></div>
</form>
</div>
</div>
</div>
</div>
AND HERE IS THE SCREENSHOT OF THAT 'CONTAINER-2'
Firstly make sure all your inputs are under one form and one view.
Use required=True in your Django form in order to make sure every input is entered.
If you are using Django forms, for example
from django import forms
class FooForm(forms.Form):
email = forms.EmailField(max_length=100,required=True,
widget=forms.TextInput(
attrs={ 'required': 'true' }),
)
In your view use the form is_valid method
form = FooForm(request.POST)
if form.is_valid():
# Complete Your Business Logic
...
return redirect("redirect_view")
# Else Return With Error Message
Use the form to save your data. If using Django form is not an option, you have to use javascript to disable the button until all inputs are not filled up
I'm working on a Django project where I would like using some customized checkbox forms when this issue shown up. Both code chunks are exactly the same, but using different forms. The issue comes when the first's sample label is clickable (so I can hide the radio button), but the second one is not working as expected, the user must click on the radio button, if I hide it the whole label becomes useless.
WORKING PROPERLY:
<form action="" class="form-group" method="POST">
<div class="modal-body">
<div class="row">
<div class="col">
<ul>
{% csrf_token %}
<fieldset >
{% for radio in form_emp.producto %}
<li style="list-style-type:none">
<span class="radio">{{ radio.tag }}
<label class="label" for="{{ radio.id_for_label }}">
{{ radio.choice_label }}
</label>
</span>
</li>
{% endfor %}
</fieldset>
</ul>
</div>
<div class="col">
{{form_emp.cantidad.label}}
{{form_emp.cantidad}}
{{form_emp.observaciones.label}}
{{form_emp.observaciones}}
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-light" type="button" data-bs-dismiss="modal">Volver</button>
<input type="submit" class="btn btn-primary" value="Agregar" />
</div>
NOT WORKING PROPERLY:
<form action="" class="form-group" method="POST">
<div class="modal-body">
<div class="row">
<div class="col">
<ul>
{% csrf_token %}
<fieldset >
{% for radio in form_pizzas.producto %}
<li style="list-style-type:none">
<span class="radio">{{ radio.tag }}
<label class="label" for="{{ radio.id_for_label }}">
{{ radio.choice_label }}
</label>
</span>
</li>
{% endfor %}
</fieldset>
</ul>
</div>
<div class="col">
{{form_pizzas.cantidad.label}}
{{form_pizzas.cantidad}}
{{form_pizzas.observaciones.label}}
{{form_pizzas.observaciones}}
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-light" type="button" data-bs-dismiss="modal">Volver</button>
<input type="submit" class="btn btn-primary" value="Agregar" />
</div>
FORMS.PY
#WORKING FORM
class CartEmpanadasForm(ModelForm):
lista_prod=Producto.objects.filter(categoria=1)
producto=forms.ModelChoiceField(widget=forms.RadioSelect, queryset=lista_prod)
class Meta:
model=Cart
fields=["producto","cantidad","observaciones"]
#NOT WORKING FORM
class CartPizzasForm(ModelForm):
#LISTA DE PRODUCTOS, FILTRO POR CATEGORÍA
lista_prod=Producto.objects.filter(categoria=2)
#MOSTRAR LOS ELEMENTOS COMO UN CHOICEFIELD
producto=forms.ModelChoiceField(widget=forms.RadioSelect, queryset=lista_prod)
class Meta:
model=Cart
fields=["producto","cantidad","observaciones"]
CSS File
label{
width: 100%;
border: 3px solid #1881f9;
position: relative;
margin: 5% 5% 5% 5%;
border-radius: 10px;
background-color: rgb(178, 201, 243);
transition: 5ms;}
input[type="radio"]:checked+label{
background-color: orange;
border: 6px solid #f95818;
box-shadow: 5px 5px rgb(178, 201, 243);}
I hope you guys could help me figure out what is going on there! Thank you so much in advance! Have a nice week!
The issue was that I was showing more than one form in the same view, as default the form's tag-id are "id_columnname_n", so the multiple forms weren't allowing to identify the tags properly. The label id was repeated.
I solved introducing customized ids in the forms.py file and setting manually every label-tag in the template.
FORMS.py
class CartEmpanadasForm(ModelForm):
#LISTA DE PRODUCTOS, FILTRO POR CATEGORÍA
lista_prod=Producto.objects.filter(categoria=1)
#MOSTRAR LOS ELEMENTOS COMO UN CHOICEFIELD
producto=forms.ModelChoiceField(widget=forms.RadioSelect(attrs={'name': 'empanada','id':'empanada'}), queryset=lista_prod)
class Meta:
model=Cart
fields=["producto","cantidad","observaciones"]
VIEW.html
<fieldset >
{% for radio in form_emp.producto %}
<li style="list-style-type:none">
<span class="radio">{{ radio.tag }}
<label class="label" for="empanada_{{forloop.counter0}}">
{{ radio.choice_label }}
</label>
</span>
</li>
{% endfor %}
I am trying to render the data from the database one by one by it does not work.
index.html
{% for i in edus %}
<div class="panel panel-default">
<div class="panel-heading" role="tab" id="headingOne">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#collapseOne" aria-expanded="true" aria-controls="collapseOne">{{i[0].title}}
</a>
</h4>
</div>
<div id="collapseOne" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingOne">
<div class="panel-body">
<div class="row">
<div class="col-md-12">
<p>{{i[0].descripiton}} </p>
</div>
</div>
</div>
</div>
</div>
{% endfor %}
If you want to render specific index, you should change:
{{i[0].title}} into {{ i.0.title }}
{{i[0].descripiton }} into {{ i.0.description }}
I'm building a website using Django.
And for somereason, the dictionary using all the forms is not showing at all..
When I click my Edit button the modal is showing without the forms...
forms.server_id needs to contain all the forms using server_id...
the server_id I use to show the previous data when I edit.
But for some reason, it doesn't show any form at all...
index.html -
{% load static i18n util_filters %}
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/bs4/jq-3.2.1/jq-3.2.1/dt-1.10.16/af-2.2.2/b-1.4.2/fc-3.2.3/fh-3.1.3/kt-2.3.2/r-2.2.0/rg-1.0.2/rr-1.2.3/sc-1.4.3/sl-1.2.3/datatables.min.css"/>
<script src="https://use.fontawesome.com/3c2c6890cf.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/v/bs4/jq-3.2.1/jq-3.2.1/dt-1.10.16/af-2.2.2/b-1.4.2/fc-3.2.3/fh-3.1.3/kt-2.3.2/r-2.2.0/rg-1.0.2/rr-1.2.3/sc-1.4.3/sl-1.2.3/datatables.min.js"></script>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="{% url 'serverlist' %}">DevOps Map</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="{% url 'serverlist' %}">Servers</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{% url 'serverlist' %}">Switches</a>
</li>
</ul>
</div>
</nav>
<style type="text/css">
.wrapper {
display:flex;
}
</style>
</head>
<body>
<div class="container">
<br>
<center><h1 class="display-4">DevOps Server List</h1></center>
<br>
<center><button type="button" class="save btn btn-outline-success btn-lg" data-toggle="modal" data-target=".AddServer">Add Server <i class="fa fa-server fa-lg" aria-hidden="true"></i></button></center>
<table class="table table-hover table-bordered table-condensed" cellspacing="0" width="1300" id="ServerTable">
<thead>
<tr>
<th><center> #</center></th>
<th><center> Server Name </center></th></center>
<th><center> Owner </center></th></center>
<th><center> Project </center></th></center>
<th><center> Description </center></th></center>
<th><center> IP Address </center></th></center>
<th><center> ILO </center></th></center>
<th><center> Rack </center></th></center>
<th><center> Status </center></th></center>
<th><center> Actions </center></th></center>
</tr>
</thead>
<tbody>
{% for server in posts %}
<tr>
<div class ="server">
<td></td>
<td><center>{{ server.ServerName }}</center></td>
<td><center>{{ server.Owner }}</center></td>
<td><center>{{ server.Project }}</center></td>
<td><center>{{ server.Description }}</center></td>
<td><center>{{ server.IP }}</center></td>
<td><center>{{ server.ILO }}</center></td>
<td><center>{{ server.Rack }}</center></td>
<td><h4><span class="badge badge-success">Online</span></h4></td></center>
<td>
<button type="button" class="btn btn-outline-danger" data-toggle="modal" href="#delete-server-{{server.id}}"
data-target="#Del{{server.id}}">Delete <i class="fa fa-trash-o"></i></button>
<button type="button" class="btn btn-outline-primary" data-toggle="modal" href="#edit-server-{{server.id}}"
data-target="#Edit{{server.id}}"> Edit <i class="fa fa-pencil"></i></button>
<div id ="Del{{server.id}}" class="modal fade" role="document">
<div class="modal-dialog" id="delete-server-{{server.id}}">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Delete Confirmation</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form action="{% url 'delete_post' server.id %}" method="post">{% csrf_token %}
<h6>Are you sure you want to delete {{ server.ServerName }}?</h6>
<br>
<center><input type="submit" class="btn btn-danger btn-md" value="Confirm"/>
<button type="submit" class="btn btn-secondary" data-dismiss="modal">Cancel</button></center>
</form>
</div>
</div>
</div>
</div>
<div class="modal fade bd-example-modal-sm" id="Edit{{server.id}}" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Edit Server <strong>{{ server.ServerName }}</strong> </h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
{% with server.id as server_id %}
{% with forms|get_by_key:server_id as edit_form %}
<form action="{% url 'edit_post' server_id %}" method="post"> {% csrf_token %}
<!--<center> {{ edit_form.as_p }} </center> -->
{% for field in forms.server_id %}
<div class="fieldWrapper">
{{ field.errors }}
<!-- {{ field.label_tag }} -->
<small><strong>{{ field.html_name }}<p align="left"></b> {{ field }}</small> </strong>
{% if field.help_text %}
<p class="help">{{ field.help_text|safe }}</p>
{% endif %}
</div>
{% endfor %}
</div>
<div class="wrapper">
<h2><button type="submit" class="save btn btn-success btn-lg">Confirm</button></h2>
<h2><button type="submit" class="btn btn-secondary btn-lg" data-dismiss="modal">Cancel</button></h2>
</div>
</form>
{% endwith %}
{% endwith %}
</div>
</td>
</tr>
{% endfor %}
</tbody>
</h5>
</table>
<div class="modal fade AddServer" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Add Server</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form method="post" novalidate> {% csrf_token %}
<!--<center> {{ form.as_p }} </center> -->
{% for field in form %}
<div class="fieldWrapper">
{{ field.errors }}
<!-- {{ field.label_tag }} -->
<small><strong>{{ field.html_name }}</strong></small><p align="left"></b> {{ field }} </p>
{% if field.help_text %}
<p class="help">{{ field.help_text|safe }}</p>
{% endif %}
</div>
{% endfor %}
</div>
<div class="wrapper">
<h2><button type="submit" class="save btn btn-success btn-lg" >Confirm</button></h2>
<h2><button type="submit" class="btn btn-secondary btn-lg" data-dismiss="modal">Cancel</button></h2>
</div>
</div>
</form>
</div>
</div>
</div>
views.py -
# Create your views here.
from django.shortcuts import render_to_response
from django.shortcuts import get_object_or_404
from django.shortcuts import render, redirect
from django.template import RequestContext
from django.views.generic import TemplateView, UpdateView, DeleteView, CreateView
from DevOpsWeb.forms import HomeForm
from DevOpsWeb.models import serverlist
from django.core.urlresolvers import reverse_lazy
from simple_search import search_filter
from django.db.models import Q
class HomeView(TemplateView):
template_name = 'serverlist.html'
def get(self, request):
form = HomeForm()
query = request.GET.get("q")
posts = serverlist.objects.all()
forms = {}
if query:
posts = serverlist.objects.filter(Q(ServerName__icontains=query) | Q(Owner__icontains=query) | Q(Project__icontains=query) | Q(Description__icontains=query) | Q(IP__icontains=query) | Q(ILO__icontains=query) | Q(Rack__icontains=query))
else:
posts = serverlist.objects.all()
#for post in posts:
# form = HomeForm(instance=post)
for post in posts:
forms[post.id] = HomeForm(instance=post)
args = {'form' : form,'forms': forms, 'posts' : posts}
#args = {'form' : form, 'forms': forms, 'posts' : posts}
return render(request, self.template_name, args)
def post(self,request):
form = HomeForm(request.POST)
posts = serverlist.objects.all()
if form.is_valid(): # Checks if validation of the forms passed
post = form.save(commit=False)
post.save()
#form = HomeForm()
return redirect('serverlist')
for post in posts:
forms[post.id] = HomeForm(instance=post)
args = {'form' : form, 'forms': forms, 'posts' : posts}
#args = {'form' : form,'forms': forms, 'posts' : posts}
return render(request, self.template_name,args)
class PostDelete(DeleteView):
model = serverlist
success_url = reverse_lazy('serverlist')
class PostEdit(UpdateView):
template_name = 'serverlist.html'
model = serverlist
form_class = HomeForm
#fields = ['ServerName','Owner','Project','Description','IP','ILO','Rack','Status']
success_url = reverse_lazy('serverlist')
#def get_object(self):
# obj = get_object_or_404(Calification, pk=self.request.POST.get('pk'))
# return obj
This :
{% with server.id as server_id %}
{# ... #}
{{ forms.server_id.as_p }}
just cannot work - it will look for forms["server_id"] (=> use the literal string "server_id" as key). You will need a custom template filter, such as the one described here. And as Daniel Roseman rightly mentions in a comment, you'll have to pass whatever server is supposed to be to your template's context too.
Also note that you're going to get a NameError in HomeView.post - you copy-pasted part of the code filling in your posts dict but not the part instanciating it. You should really factor this out instead of copy-pasting.
I have a end_date field on my news apps which is a facultative field.
When a author is editing one of his new and erase the end_date, I set in the model the end_date to None.
My problem is that the field then display the value 'None' on next edit instead of just being blank.
Here is my field :
models.py
end_date = models.DateTimeField(null=True, blank=True)
forms.py
end_date = forms.CharField(label='', required=False, widget=forms.DateTimeInput(attrs={'class': 'form-control', 'format': 'DD, d MM yy', 'placeholder': _('End date')}))
and the assignation in my view :
views.py
if news_form.cleaned_data['end_date'] == '' :
edited_new.end_date = None
edited_new.save()
EDIT :
here is my template :
news.html
<form action="#" method="post" role="form" id="news-form">{% csrf_token %}
{{ news_form.media }}
<div class="col-xs-12">
<div class="panel panel-primary">
<div class="panel-heading">
<div class="row">
<div class="col-xs-12 col-md-6">
<h2 class="panel-title">{% trans "Add or edit news" %}</h2>
</div>
<div class="col-xs-12 col-md-6">
<div class="pull-right">
<span class="glyphicon glyphicon-floppy-remove"></span> {% trans "Cancel" %}
<button type="submit" class="btn btn-primary form-btn save"><span class="glyphicon glyphicon-floppy-saved"></span><span class="button-text"> {% trans "Save" %}</span></button>
</div>
</div>
</div>
</div>
<div class="panel-body">
<div class="row">
<div class="col-xs-12 col-md-6">
{{ news_form.title }}
</div>
<div class="col-xs-4 col-md-2">
{% trans 'Tag' %}
</div>
<div class="col-xs-8 col-md-4">
{{ news_form.tag }}
</div>
</div>
<div class="row">
<div class="col-xs-12 no-label-field redactor-field">
{{ news_form.message }}
</div>
</div>
<div class="row">
<div class="col-xs-6 date-field no-label-field">
<div class="form-group">
<div class='input-group date datetimepicker'>
{{ news_form.start_date }}
<span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
<div class="col-xs-6 date-field no-label-field">
<div class="form-group">
<div class='input-group date datetimepicker'>
{{ news_form.end_date }}
<span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12">
{{ news_form.active }} {% trans 'Activate the news' %}
</div>
</div>
</div>
</div>
</div>
<span style="display:none;">{{ news_form.id }}</span>
</form>
You can use the filter default_if_none available since Django 1.3, it'll only work for values that are None.
{{ news_form.end_date|default_if_none:'' }}
Docs