How to display choicefield select widget on template? - django

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

Related

Every form validation in formset

Some troubles with validation.
I'm using this construction in my template:
<form method="POST">
{% csrf_token %}
{{ formset.media.js }}
{% for form in formset %}
<p>{{ form }}</p>
{% endfor %}
<button type="submit" class="btn btn-primary">Send</button>
And this validation in views:
def flow_type(request):
patternFormset = modelformset_factory(CashFlowPattern, fields='__all__')
if request.method == 'POST':
formset = patternFormset(request.POST)
if formset.is_valid():
formset.save()
formset = patternFormset()
template = 'cash_table/index.html'
context = {
# 'form': form,
'formset': formset
}
return render(request, template, context)
I get form at page but nothing happens after submit.
But if I use another template construction it works:
<form method="POST">
{% csrf_token %}
{{ formset.media.js }}
{{ formset }}
<button type="submit" class="btn btn-primary">Send</button>
</form>
But then I get all fields of new form at the same line.
I think you need to have {{ formset.management_form }} in the template where you iterate through the forms of the formset so that Django knows that it is a formset, and knows how many forms are in the formset, etc...
<form method="POST">
{% csrf_token %}
{{ formset.management_form }}
{{ formset.media.js }}
{% for form in formset %}
<p>{{ form }}</p>
{% endfor %}
<button type="submit" class="btn btn-primary">Send</button>
When you use {{ formset }} the management is done automatically (it's a shortcut).
Source: https://docs.djangoproject.com/en/4.1/topics/forms/formsets/#custom-formset-validation

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.

Django form field doesn't appear on the template

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?

haystack on existing template

How to implement working SearchView in existing views.py?
I already have CBV, and added in urls.py as /moderate and want to apply search form in it. but always got "Results No results found."
This is my /moderate page with 3 forms, using SearchView and piece of code from tutorial in template.
And this from /search page, with urls(r'^search/$', include('haystack.urls'))
urls.py
urlpatterns= [
url(r'^search/', include('haystack.urls')),
url(r'^moderate/', Moderate.as_view(), name='moderate'),
]
views.py
class Moderate(SearchView):
#method_decorator(staff_member_required)
def dispatch(self, *args, **kwargs):
return super(Moderate, self).dispatch(*args, **kwargs)
#model = Ad
template_name = 'adapp/ad_moderate.html'
#template_name = 'search/search.html'
paginator_class = DiggPaginator
paginate_by = 10
ad_type = None
ad_sub_type = None
def get_queryset(self):
qs = super(Moderate, self).get_queryset().filter(ad_type__isnull=False,
ad_sub_type__isnull=False)
return qs
def get_context_data(self, **kwargs):
context = super(Moderate, self).get_context_data(**kwargs)
context['filter'] = ModerateFilter(self.request.GET)
return context
# define method to recieve fields from form, and change data accordings
def post(self, request, *args, **kwargs):
selected = request.POST['selected']
record = Ad.objects.get(pk=int(selected))
form = ModerateForm(request.POST, instance=record)
if form.is_valid():
form.save(commit=True)
return HttpResponseRedirect('')
template/ad_moderate.html
{% extends 'base.html' %}
{% load i18n url_tags %}
{% block content %}
<div id="casing">
<div id="content">
{# filter form, to show only models with moderated=True #}
<form action="" method="get">
{{ filter.form.as_p }}
<input type="submit">
</form>
<h2>Search</h2>
{# search form right from tutorial #}
<form method="get" action="">
<table>
{{ form.as_table }}
<tr>
<td> </td>
<td>
<input type="submit" value="Search">
</td>
</tr>
</table>
{% if query %}
<h3>Results</h3>
{% for result in page.object_list %}
<p>
{{ result.object.title }}
</p>
{% empty %}
<p>No results found.</p>
{% endfor %}
{% else %}
{# Show some example queries to run, maybe query syntax, something else? #}
{% endif %}
</form>
{% for object in filter %}
{# a lot of template tags and third form to change value of model #}
<form action="" method="POST">
{% csrf_token %}
<input type="radio" name="moderated" value="True">Accept
<br>
<input type="radio" name="moderated" value="False">Decline
<input type="hidden" value="{{ object.id }}"
name="selected">
<input class="btn" type="submit" value="moderate">
</form>
search_indexes.py
from .models import Ad
class AdIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
def get_model(self):
# my model, with one search should be
return Ad
templates/search/indexes/app/ad_text.txt
{{ object.title }}
{{ object.short_desc }}
{{ object.description }}
{{ object.experience }}
{{ object.skills }}
{{ object.name }}
{{ object.city }}
get_context_data():
context['search'] = SearchForm(self.request.GET).search()
Would solve a problem.
That means, I should create form and send return from .save() method, rather that django-like form instance.

How insert 2 different forms on the same page in Django

I have to insert 2 forms in the same page:
1) Registration form
2) Login form
.
So if I use this in the views.py:
if request.method == 'POST':
form = registrationForm(request.POST)
if form.is_valid():
form.save()
return render_to_response('template.html', {
'form': form,
})
I will get error by submitting one of two forms.
How can I distinguish the 2 forms submitting in the views ?
You can also do like this,
<form method='POST'>
{{form1.as_p}}
<button type="submit" name="btnform1">Save Changes</button>
</form>
<form method='POST'>
{{form2.as_p}}
<button type="submit" name="btnform2">Save Changes</button>
</form>
CODE
if request.method=='POST' and 'btnform1' in request.POST:
do something...
if request.method=='POST' and 'btnform2' in request.POST:
do something...
You can submit two forms on the same page... but the action that each form calls (i.e. the view function that will process each form) should probably be different. That way, you won't have to try and distinguish the forms.
e.g. On your page:
<form id="login_form" action="{% url app.views.login %}" method="post">
...form fields...
</form>
<form id="registration_form" action="{% url app.views.registration %}" method="post">
...form fields...
</form>
And so, in views.py, you'll have a login() view function and a registration() view function that will handle each of those forms.
<form action="Page where u want to post the data" method="post">
<input name="edit" type="submit" value="Edit Client">
<input name="delete" type="submit" value="Delete Client">
</form>
just Give different names to the buttons.
if request.method == "POST" and 'edit' in request.POST:
/ Do /
if request.method == "POST" and 'delete' in request.POST:
/Do /
You can post both forms to same url too:
forms in template are like this:
<form method="post" action="/profile/">
{% for field in firstform %}
<div class="mb10">
<div class="fl desc">{{ field.label_tag }}<br />
<div class="fr">{{ field }}{{ field.errors }}</div>
<div class="clear"></div>
</div>
{% endfor %}
{% for field in secondform %}
<div class="mb10">
<div class="fl desc">{{ field.label_tag }}<br /><</div>
<div class="fr">{{ field }}{{ field.errors }}</div>
<div class="clear"></div>
</div>
{% endfor %}
<a class="submit fr" href="#""><img src="{{ MEDIA_URL }}img/save.png" /></a>
</form>
and just handle them like this in view:
if request.method == 'POST':
firstform = ProfileForm(request.POST, request.FILES, instance=profile)
secondform = UserForm(request.POST, instance=request.user)
and then do stuff with firstform&secondform.
You can have both forms posting to the same URL and have a hidden input with name set to login or registration and sort that out on the server
You can do the Registration and Login POST to different urls so each POST will be handled by corresponding view