Django form won't display - python

I'm working on a project and we need to add a form to add an event. It lists the name, date, time, and address. I got the form to work but when I added the base, the form doesn't show up on the web page with the base loaded. I'm thinking it has something to do with my html file. Here is my html file.
{% extends "base.html" %}
{% block heading %}My Events{% endblock %}
{% block content3 %}
</h1><b><font size="5">Save Event</b></h1></font>
<form method="POST" action=".">{% csrf_token %}
{{form.as_p}}
<input type ="submit" value="Add Event"/>
</form>
{% endblock %}
views:
def add_event(request):
user = request.user
events = user.event_set.all()
if request.method == "POST":
form = EventForm(request.POST)
if form.is_valid():
event = Event.objects.create(
eventname = form.cleaned_data['eventname'],
eventdate = form.cleaned_data['eventdate'],
eventtime = form.cleaned_data['eventtime'],
address = form.cleaned_data['address'],
user = request.user
)
return HttpResponseRedirect('/')
else:
form = EventForm()
variables = RequestContext(request, {
'form': form
})
return render_to_response('add_event.html',variables)
base:
HTML (base.html)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>DelMarVa Happenings | {% block title %}{% endblock %}</title>
<link rel="stylesheet" href="/site_media/style.css" type="text/css" />
</head>
<body>
<div id="wrapper">
<div id="masthead">
<div id="logo">
<img src="/site_media/Delmarva.gif" width="100px" height="80px" />
</div>
<h1>DelMarVa Happenings</h1>
<br />
<h4>A listing of events in and around Delaware, Maryland, and Virginia</h4>
</div>
<div id="nav">
{% if user.is_authenticated %}
<h3>welcome, {{ user.username }}</h3>
{% else %}
<h3>welcome, guest</h3>
{% endif %}
<ul>
<li><a href="/">home<a/></li>
{% if user.is_authenticated %}
<li>add event</li>
<li>my events</li>
<li>my account</li>
<li>logout</li>
{% else %}
<li>login</li>
<li>register</li>
{% endif %}
</ul>
</div>
<div id="ads">
<img src="/site_media/ad.jpg" />
</div>
<div id="main">
<h2>{% block head %}{% endblock %}</h2>
{% block content %}{% endblock %}
</div>
</div>
</body>
</html>

Your base.html does not have a {% block content3 %} - rename the block name in base, or the extended template to match each other.

Make sure to leave space between form.as_p and the braces. As such, {{ form.as_p }}

Related

Django basic ModelForm not showing choices

Using Django tutorial, I built a basic ModelForm with choice fields:
One field (Shirt size) - is not showing choices
Second field - not showing at all
I can't find the reason, anywhere I checked it seems like I'm doing things right, but obviously I'm not.
Thank you.
The Result Form
views.py
def person(request):
if request.method == 'POST':
form = forms.PersonForm(request.POST)
if form.is_valid():
return HttpResponseRedirect('/thanks/')
else:
form = forms.PersonForm()
return render(request, 'development/form_template.html', {'form': form})
forms.py
class PersonForm(ModelForm):
class Meta:
model = models.Person
fields = '__all__'
models.py
class Person(models.Model):
SHIRT_SIZES = (
('S', 'Small'),
('M', 'Medium'),
('L', 'Large'),
)
name = models.CharField(max_length=60, default='Anonymous', help_text='Type your name.')
shirt_size = models.CharField(max_length=1, choices=SHIRT_SIZES)
medal_type = models.TextChoices('MedalType', 'GOLD SILVER BRONZE')
form_template.html
{% extends 'development/development_template.html' %}
{% block content %}
<div class="container">
<form action="/your-name/" method="post">
{% csrf_token %}
<table>
{{ form.as_table }}
</table>
<input type="submit" value="Submit">
</form>
</div>
{% endblock content %}
CSS files I'm using
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.css" type="text/css" rel="stylesheet" media="screen,projection"/>
<link type="text/css" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<link type="text/css" rel="stylesheet" href="{% static 'css/style.css' %}">
The problem was 100% the support of Materializecss design in select - for some reason it's not supporting select anymore.
I used bootstrap4 to execute the form pages:
(1) install: pip install django-bootstrap4
(2) add to INSTALLED_APPS = [..., 'bootstrap4',]
(3) edit your HTML form
Here's html for example:
{% extends 'adolim/adolim_template.html' %}
{% block content %}
{% load bootstrap4 %}
{# Load CSS and JavaScript #}
{% bootstrap_css %}
{% bootstrap_javascript jquery='full' %}
{# Display django.contrib.messages as Bootstrap alerts #}
{% bootstrap_messages %}
<div class="container" style="width:100%;" dir="rtl">
<div class="col s3 right">
</div>
<div class="col s6 right" dir="rtl">
<div class="container">
<div class="row"><br></div>
<h4 class="right">{{ page_title }}</h4>
<div class="row"><br></div>
<form dir="rtl" action="{% url 'adolim:add_order' %}" method="post" >
{% csrf_token %}
{% bootstrap_form form %}
<div class="col center">
{% buttons %}
<button class="btn-large waves-effect waves-light blue darken-1" type="submit" name="action">{{ page_title }} למערכת
<i class="material-icons right">send</i>
</button>
{% endbuttons %}
</div>
</form>
</div>
</div>
</div>
{% endblock content %}

Page does not redirect on click but other buttons work/redirect properly?

I have a page that contains a form. It has 3 buttons, Enter/Leave and Options. My enter and leave button operate just fine, but the options button is supposed to redirect to a list of entries and currently it does not do anything, not even produce errors, which I can't figure out why it's happening.
I feel like I'm missing something very slight, I tried moving the Manager Options button into the form tags but this did not work either, so I'm not sure I'm missing an important piece as I am fairly new to Python/Django.
views.py
class EnterExitArea(CreateView):
model = EmployeeWorkAreaLog
template_name = "operations/enter_exit_area.html"
form_class = WarehouseForm
def form_valid(self, form):
emp_num = form.cleaned_data['adp_number']
if 'enter_area' in self.request.POST:
form.save()
return HttpResponseRedirect(self.request.path_info)
elif 'leave_area' in self.request.POST:
form.save()
EmployeeWorkAreaLog.objects.filter(adp_number=emp_num).update(time_out=datetime.now())
return HttpResponseRedirect(self.request.path_info)
elif 'manager_options' in self.request.POST:
return redirect('enter_exit_area_manager_options_list')
class EnterExitAreaManagerOptionsList(ListView):
filter_form_class = EnterExitAreaManagerOptionsFilterForm
default_sort = "name"
template = "operations/list.html"
def get_initial_queryset(self):
return EmployeeWorkAreaLog.active.all()
def set_columns(self):
self.add_column(name='Employee #', field='adp_number')
self.add_column(name='Work Area', field='work_area')
self.add_column(name='Station', field='station_number')
urls.py
urlpatterns = [
url(r'enter-exit-area/$', EnterExitArea.as_view(), name='enter_exit_area'),
url(r'enter-exit-area-manager-options-list/$', EnterExitAreaManagerOptionsList.as_view(), name='enter_exit_area_manager_options_list'),
]
enter_exit_area.html
{% extends "base.html" %}
{% block main %}
<form id="warehouseForm" action="" method="POST" novalidate >
{% csrf_token %}
<div>
<div>
{{ form.adp_number.help_text }}
{{ form.adp_number }}
</div>
<div>
{{ form.work_area.help_text }}
{{ form.work_area }}
</div>
<div>
{{ form.station_number.help_text }}
{{ form.station_number }}
</div>
</div>
<div>
<div>
<button type="submit" name="enter_area" value="Enter">Enter Area</button>
<button type="submit" name="leave_area" value="Leave">Leave Area</button>
</div>
</div>
</form>
{% endblock main %}
{% block panel_footer %}
<div class="text-center">
<button type="submit" name="manager_options" value="Options">
Manager Options
</button>
</div>
{% endblock panel_footer %}
list.html
{% extends "base.html" %}
{% load core_tags staticfiles %}
{% block head %}
<script src="{% static "js/operations/enter_exit_area_manager_options_list.js" %}"></script>
{% endblock head %}
{% block main %}
{% include 'core/list_view/list.html' %}
{% endblock main %}
You option buttons is really link to another page so you should add it to your template like this. Replacing button-styles class with however you want your button to look.
<a href="{% url 'enter_exit_area_manager_options_list' %}" class="button-styles">
Manager Options
</a>

How Django validates form?

I have a little issue. For example, I have this view:
def post_create(request):
form = PostForm(request.POST or None)
if form.is_valid():
instance = form.save(commit=False)
instance.save()
# message success
messages.success(request, "Successfully Created")
return HttpResponseRedirect(instance.get_absolute_url())
else:
messages.error(request, "Not Successfully Created")
context = {
"form": form,
}
return render(request, "post_form.html", context)
Main problem: after redirect I have both messages (if and else at the same time). WHY?
Solution is:
... ...
return HttpResponseRedirect(instance.get_absolute_url())
elif form.errors:
messages.error(request, "Not Successfully Created")
context = {
"form": form,
}
return render(request, "post_form.html", context)
But why I see both of messages when I redirect after success validation (1st variant)?
base.html:
{% load staticfiles %}
<!--DOCTYPE html -->
<html>
<head>
<title></title>
<link rel='stylesheet' href='{% static "css/base.css" %}' />
<style>
{% block style %}{% endblock style %}
</style>
</head>
<body>
{% include "messages_display.html" %}
<div class='container'>
{% block content %}{% endblock content %}
</div>
</body>
</html>
messages_display.html:
{% if messages %}
<div class='messages'>
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{% if "html_safe" in message.tags %}{{ message|safe }}{% else %}{{ message }}{% endif %}</li>
{% endfor %}
</ul>
</div>
{% endif %}
post_form.html:
{% extends "base.html" %}
{% block content %}
<div class='col-sm-6 col-sm-offset-3'>
<h1>Form</h1>
<form method='POST' action=''>{% csrf_token %}
{{ form.as_p }}
<input type='submit' class='btn btn-default' value='Create Post' />
</form>
</div>
{% endblock content %}

Unclosed tag 'block'. Looking for one of: endblock

<!--this is my base.html file -->
<!DOCTYPE html>
<html lang="en">
<head>
<title>Jumbotron Template for Bootstrap</title>
</head>
<body>
{% block content %} {% endblock %}
<p>© Company 2014</p>
</body>
</html>
<!-- this is my signup.html file-->
{% extends "base.html" %}
{% block title %}
<form method = 'POST' action = ''>{% csrf_token %}
<label for="your_name">Your name: </label>
{{form.as_p}}
<input type = 'submit'>
</form>
{ % endblock % }
I am just getting error
"Unclosed tag 'block'. Looking for one of: endblock"
Please help.
It is important not to add extra spaces and follow the syntax. Replace:
{ % endblock % }
with:
{% endblock %}
Just change {% block title %} to {% block content %}.

registration_complete template not shown with 0.8 version of django-registration

I was previously using 0.6 version of django-registration.Now I upgraded to 0.8 ,and some issues are cropping up in my webapp
I have in the templates/registration folder ,these files needed for register(among others)
activation_complete.html
activation_email.txt
activation_email_subject.txt
registration_form.html
registration_complete.html
The registration_form.html is
{% extends "registration/auth_base.html" %}
{% block content %}{{block.super}}
<div class="subtitle short">Register</div>
<div id="registerform" class="box half">
<form action="/myapp/account/register/" method="POST">{% csrf_token %}
{% if form.non_field_errors %}
{{ form.non_field_errors }}
{% endif %}
<fieldset class="registerfields">
<p><label for="id_username">Username:</label> {{ form.username }}</p>
{% if form.username.errors %}<p class="error">{{ form.username.errors }}</p>{% endif %}
<p><label for="id_email">EmailAddress:</label>{{ form.email }}</p>
{% if form.email.errors %}<p class="error">{{ form.email.errors }}</p>{% endif %}
<p><label for="id_password1">Password:</label>{{ form.password1 }}</p>
{% if form.password1.errors %}<p class="error">{{ form.password1.errors }}</p>{% endif %}
<p><label for="id_password2">Password(again):</label>{{ form.password2 }}</p>
{% if form.password2.errors %}<p class="error">{{ form.password2.errors }}</p>{% endif %}
<p>
<input type="submit" value="Submit" />
</p>
</fieldset>
</form>
</div>
{% endblock %}
The template registration_complete.html is as below
{% extends "registration/auth_base.html" %}
{% block content %}{{block.super}}
<p id="message">Registration Complete! Check your email</p>
{% endblock %}
Also here is the auth_base.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Myapp{% block title %} {% endblock %}</title>
<LINK REL=StyleSheet HREF="{{MEDIA_URL}}css/myapp.css" TYPE="text/css" MEDIA="screen, print"/>
<link rel="shortcut icon" href="{{ MEDIA_URL }}img/myapp-icon.ico"/>
</head>
<body>
<div id="content">
{% block content %}
{% endblock %}
</div>
<div id="sidebar">
<h3> page info </h3>
{% block whatis %}
{% endblock %}
</div>
<div id="homelnk">
<img class="centerpage" src="{{ MEDIA_URL }}img/home.png">
</div>
</body>
</html>
But when I submit a new user details for registration,I am not getting this registration_complete page.I still get a registration form with blank fields
Still,the activation link is sent to the email , and I am able to login as the new user..Why is the registration_complete page not shown?This used to work in the older version of django-registration ..I couldn't find anything in the upgrade guide regarding the templates..
Any advice appreciated
I use this template for registration_form.html:
{% extends "base.html" %}
{% load i18n %}
{% block content %}
<form method="post" action=".">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="{% trans 'Submit' %}" />
</form>
{% endblock %}
You can find more of those here :
https://github.com/nathanborror/django-registration/tree/master/registration/templates/registration

Categories