How to add display dropdown fields in Django - python

I'm trying to add a category field to my blog posts model in Django. When I make a post with the admin panel it shows the choices in a drop down list, however I wish to display choices in html.
Here is the form in my HTML file:
<div class="container">
<div class="row">
<div class="col-lg-7 offset-lg-1">
<form class="create-form" method="POST" enctype="multipart/form-data">{% csrf_token %}
<!-- title -->
<div class="form-group">
<label for="id_title">Title</label>
<input class="form-control" type="text" name="title" id="id_title" placeholder="Title" required autofocus>
</div>
<!-- Body -->
<div class="form-group">
<label for="id_body">Content</label>
<textarea class="form-control" rows="10" type="text" name="body" id="id_body" placeholder="Put the description of your post here..." required></textarea>
</div>
<div class="form-group">
<label for="id_category">Category</label>
<select class="form-control" name="category" id="id_category" required></select>
</div>
<!-- Image -->
<div class="form-group">
<label for="id_image">Image</label>
<input type="file" name="image" id="id_image" accept="image/*" required>
</div>

I also asked these types of questions about Django in StackOverflow. However, it is really hard to explain your questions as a newbie to experienced people so I will not just answer your question but also I want to show you the path to do it.
I think there are multiple parts to your question. It is not just to create a dropdown list with choices in HTML but also, you want to pass the data from your blog posts model in Django.
Firstly, let's say that the name of the HTML file is posts.html. In posts.html, to create a dropdown in an HTML is like this; (assume that your categories are zero, one and two and you can see these on dropdown list in the admin panel)
<select name="post_categories" class="filter-selectbox">
<option value="zero">"Zero"</option>
<option value="one">"One"</option>
<option value="two">"Two"</option></select>
However, if you want to create a dropdown list using your model's field, you should do similar like this: (I assumed that you can be able to create a dropdown list with your post model's field named category.)
<select name="post_categories" class="filter-selectbox">
{% for post in posts %}
<option value="{{ post.category }}">{{ post.category }}</option>
{% endfor %} </select>
So now you can pass and use the object to HTML and can be able to use its fields.
However, I assumed that you can be able to pass objects to the template. If you do not know how, there is another question that how to pass data to an HTML file? You should search more about "passing objects to template".
In views.py, when you render the template, you can be able to pass parameters or objects to use them in your template. Please look at this for that: Django: Passing object from template to views
So in your case, it should be something like this;
def get_posts(request):
posts = Post.objects.all() # In this case, I assume that I can reach category as post.category in the template
context = {"posts": posts}
return render(request, "posts.html", context)
I hope for a newbie in Django, I could explain it as simple. Keep learning.
Good Luck!

Related

Django: Prefill forms with database entries from inside a loop

I want to prefill a form with already existing database entries but can't access the correct ones.
A user can create a task and pass information on when creating it. When he wants to update it later, the already saved information should be used to prefill the form.
My problem is, that I'm inside a for-loop and it seems that I can't access the elements of the loop.
Here is what I'm doing:
I'm in a template inside a for-loop. The loop lists all tasks with an update button for every task. This button calls a form via the bootstrap data-target. Here's an example:
{% for task in tasks %}
<button class="btn-primary btn-block btn-lg" data-toggle="modal" data-target="#updateTask">Update Task</button> {% endfor %}
In my upcoming form I can't use the variables from the task element. For example the task.taskname. However, I can use all other variables like the user.first_name which exists outside the loop.
<div class="modal-body">
<form method="POST" action="{% url 'update_task' %}">
{% csrf_token %}
<div class="form-row">
<div class="form-group col-md-6">
<label for="name" class="col-form-label">Task:</label>
<input type="text" id="taskID" name="task" class="form-control" value="{{ user.first_name }}" required> -> this works
<input type="text" id="taskID2" name="task2" class="form-control" value="{{ task.taskname }}" required> -> this doesn't
</div>
<input type="submit" value="Send" class="btn btn-block custom-button">
</div>
I know I could do this with opening a completely new page but I want to try to use the data-target calling my view instead of calling the view directly.
Is there any way to pass my currently looped element to the form?
Thanks in advance!
Pascal

How to access the selected option in an select tag with Django (not using Javascript)?

I have a form that has a select tag and dynamically created options for that tag as shown below. I want to access the selected tag if it is included in the POST request as part of the form in my Python/Django code:
<form action="{% url 'newprogram' %}" method="post" novalidate>
{% csrf_token %}
TODO: Add Program to School
<select name="schooloptions">
{% for school in schools %}
<option value="{{ school.name }}">{{ school.name }}</option>
{% endfor %}
</select>
<div class="form-group">
<input autofocus class="form-control" type="text" name="programname" placeholder="">
</div>
<input class="btn btn-primary" type="submit" value="Post">
</form>
I want to select the option that the user selects from the drop-down menu as follows but it does not work:
#login_required
def newprogram(request):
if request.method == "POST":
programname = request.POST["programname"]
school = request.POST["schooloptions"].selected() #This does not work and is what I need help with
schoolobj = School.objects.get("school")
school = Program(School=schoolobj, name=programname)
school.save()
return render(request, "network/index.html")
Any thoughts as to how I can access the selected option from a select HTML tag within a form?

Python Flask jinja2 render input field onkeyup

In my app I want to check an input field e.g username if it's exists or not before continue my in form.
I'm using Flask jinja2 for templating. Here is a piece of my code:
<form method="POST" action="">
<div class="row">
<div class="form-group col-lg-9 col-md-9 col-sm-9">
<label for="inputUsername">User Name</label>
{{ render_field(form.username, class="form-control rounded" onkeyup="checkUserName()") }}
</div>
Of course the onkeyup attribut does not work, my question how to perform it ?
Thanks
Using WTForms for custom validation in my case, it's the good option

Searching with a defined query in Django / Python

Currently as it stands I have a search bar and a button on my homepage like so.
<div class="input-group">
<input id="address" type="textbox" placeholder="City or Zipcode" class="form-control">
<span class="input-group-btn">
<button class="btn btn-default" type="button" id="addressSearch">Search</button>
</span>
</div>
I have created a api.py file which is within my websites folder which looks like so.
import urllib2
import json
locu_api = '****'
def loc_search(query):
api_key = locu_api
url = 'https://api.locu.com/v1_0/venue/search/?api_key=' + api_key
locality = query.replace(' ', '%20')
final_url = url + "&locality=" + locality + "&category=restaurant"
json_obj = urllib2.urlopen(final_url)
data = json.load(json_obj)
for item in data['objects']:
print item['name']
print item['phone']
Essentially what I am trying to do is when the user search's for a city e.g. New York then the loc_search(query) is called populating the search field '(query)' with the users input and the data then being displayed.
I haven't much experience with either django or api's so any help would be invaluable. Thanks again
i'm not really experienced in django too, but have been working around for 3 months now, i will advise you to make use of the django-auto-complete-light or django-ajax-selects for your frontend search in the navigation bar, and django-salmonela for your backend fields. those are helpful. and the input tag doesn't really work with your django forms, so you'll have to use a class in your div tag and explicitly call each form field using the {{ form.fieldName }} then make use of the widget to reference your template tags, or just use the above packages which know much better how to handle your fields.
example:
within your template:
<div class="container text-center form-horizontal topSpace">
<form method="POST" enctype="multipart/form-data" action="{% url 'create-recipe' %}">
{% csrf_token %}
{{ form.non_field_errors }}
<div class="form-group">
{{ form.name.errors }}
<label for="{{ form.name.id_for_label }}" class="col-lg-4 control-label">Name:</label>
<div class="col-lg-1">
{# <input type="text" class="form-control" id="user-name" placeholder="Enter your name">#}
{{ form.name }}
</div>
</div><!-- end form-name-->
{{ form.as_p }}
<input type="submit" value="Add Recipe">
</form>
</div>
then in your form:
class RecipeForm(autocomplete_light.ModelForm, forms.ModelForm):
class Meta:
model = Recipe
exclude = []

remembering form field value on django model form

I am quite new to Django as such, and have been playing around with ModelForms. So far, I have been able to create ModelForms with ease. However, one problem seems to bug me a bit:
When a user fills the form, and if there is an error (say int instead of char or a missing blank=False value), the form spits out the error and seems to forget the values the user entered when the form failed to validate. I am wondering if there is a way to remember these values so that the user does not have to enter them again.
At the moment, I have something like the following:
class ContactForm(CreateView):
form_class = ContactForm
template_name = "superform.html"
success_url = '/ty/'
def form_valid(self, form):
# do something useful with validated form
return super(ContactForm, self).form_valid(form)
def form_invalid(self, form):
# do something useful with invalidated form.
return super(ContactForm,self).form_invalid(form)
I am assuming I need to do something in form_invalid to pass the values back to the form - but I am unsure how to do this(?).
I would really appreciate if someone could point me in the right direction.
Thanks.
----Edit---
<form class="form" role="form" action="{% url 'coolurl' %}" method="post">{% csrf_token %}
{% if form.non_field_errors %}
<div class="alert">
{% for error in form.non_field_errors %}
<span class="label">Error: {{ error|escape }}</span>
{% endfor %}
</div>
{% endif %}
<div class="form-group">
{% if form.name.errors %}
<div class="alert">
{% for error in form.name.errors %}
<span class="label">Error: {{ error|escape }}</span>
{% endfor %}
</div>
{% endif %}
<label class="col-sm-3" for="id_name">Name:</label>
<div class="col-sm-6">
<input class="form-control"
id="id_name"
type="text"
name="name"
maxlength="128"
placeholder="Your name..">
</div>
</div>
<button type="submit" class="btn btn-success">Submit</button>
</form>
Try to mention the value of the input tag:
<input class="form-control"
id="id_name"
type="text"
name="name"
maxlength="128"
value="{{ form.name.value|default_if_none:'' }}"
placeholder="Your name..">
</div>
You've taken the responsibility for rendering those fields away from Django by simply hard-coding them in the HTML. That means that Django has no way of inserting the current values; not only when redisplaying after errors, but also if you have a form that modifies existing database content.
Don't do it like that. I understand that you don't want to just juse form.as_p, but there is a good middle ground: output each field in the template with {{ form.my_field }}. You can add relevant classes to the fields in the definition in forms.py, and then Django will take care of outputting it correctly.

Categories

Resources