Reading Checkbox in Django - python

This is NOT just another Reading Django Checkbox. I've read through 7 different posts about Checkbox on here along with 4 other pages in Django Documentation. My situation is a bit different. I can't read whether a specific checkbox is checked or not. I just get a value "True" for both checkboxes even when only one checkbox is checked. If nothing is checked, it worked as expected. Do I really need to use the MultipleChoiceField?
Current Output:
- John Doe Location A True ===> Checked
- James Smith Location A True ===> Unchecked
Ideally, I would like a list of dictionary that contains
data [0] = {'John', 'Doe', 1}
data [1] = {'John', 'Smith', 0}
...
where '1' is the flag for overwrite and '0' is to ignore.
Background:
User submits a form
Second form displays the previous information with checkbox next to the names if duplicates are found. If they're not duplicate, no checkbox will appear.
Read in the checkbox, process, and display the final page.
forms.py
from django import forms
from django.forms.formsets import BaseFormSet
class NameForm (forms.Form):
first_name = forms.CharField (max_length = 20, required = False)
last_name = forms.CharField (max_length = 20, required = False)
class BaseNameFormSet (BaseFormSet):
...
class CheckBox (forms.Form):
overwrite = forms.BooleanField (required = False)
views.py
def addname (request):
....
if request.method == 'POST':
....
if formset.is_valid ():
location = request.POST ['site']
data = formset.cleaned_data
# Store data into session to be used in another method
request.session ['location'] = location
request.session ['data'] = data
def process (request):
location = request.session ['location']
data = request.session ['data']
if request.method == 'POST':
form = CheckBox (request.POST)
if form.is_valid ():
overwrite = form.cleaned_data.get ('overwrite')
# for duplicate in checkboxes:
# overwrite = duplicate.get ('overwrite')
print (overwrite)
context = {'data': data, 'location': location, 'overwrite': overwrite}
return render (request, 'nodeform/success.html', context)
return HttpResponse ('No Overwrite Data.')
response.html
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'nameform/style.css' %}" >
<title>Submitted Entries</title>
</head>
<body>
<h1>Submitted Entries:</h1>
<h4>Location: {{ location }}</h4>
<form action="process" method="POST">{% csrf_token %}
<div id="tablefont">
<table id="table01">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th class="center">Overwrite</th>
</tr>
{% for info in data %}
<tr>
<td>{{ info.first_name }}</td>
<td>{{ info.last_name }}</td>
<td class="center"><input type="checkbox" name='overwrite-{{ forloop.counter0 }}'></td> ===> Testing Checkbox
<!--
{% if info.overwrite %}
<td class="center"><input type="checkbox" name='overwrite-{{ forloop.counter0 }}'></td>
{% else %}
<td class="center"></td>
{% endif %}
-->
</tr>
{% endfor %}
</table>
</div>
<br>
{% if errors %}
<p class="errorlh">Error:
<ul>
{% for error in errors %}
<li>{{ error }}</li>
{% endfor %}
</ul>
</p>
{% endif %}
<br>
<p><input type="submit" value="Confirm">
<a href="{% url 'addname' %}">
<button type="button">Cancel</button></a></p>
</form>
</body>
</html>
success.html
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Successfully Added</title>
</head>
<body>
<h1>Information captured:</h1>
<ul>
{% for info in data %}
<li>{{ info.first_name }} {{ info.last_name }} {{ location }} {{ overwrite }}</li>
{% endfor %}
</ul>
Add more names
</body>
</html>

All your checkbox inputs have the same attribute name=overwrite so, when you check one, it will be the only one submitted in the POST overwrite=true.
You should give an unique name to each input. I suggest you to use {{ forloop.counter0 }}, it will provide the current iteration of the loop, starting from 0. Basically it is the index of the current "info" in "data".
{% for info in data %}
<tr>
<td>{{ info.first_name }}</td>
<td>{{ info.last_name }}</td>
<td class="center"><input type="checkbox" name='overwrite-{{ forloop.counter0 }}'></td> ===> Testing Checkbox
<!--
{% if info.overwrite %}
<td class="center"><input type="checkbox" name='overwrite' value="1"></td>
{% else %}
<td class="center"></td>
{% endif %}
-->
</tr>
{% endfor %}
This way, you can match the form field in POST to the "info" in the backend.

Related

Prompt Asking For Password When Pressing A Button

I would like to add a prompt everytime someone tries to press the button to 'Delete' or 'Download' a file (in my project, you can upload files with passwords, so that if someone wants to delete/download the file, he needs to enter a password).
The password itself is saved in the models.py using django - how would i be able to to so in my code (listing my viwes.py to the html code, urls.py, models.py, forms.py, HTML CODE Itself).
#login_required(login_url='login')
def My_Files(request):
files = File.objects.all()
return render(request, 'home/My Files.html', {"files" : files})
path("MyFiles", views.My_Files, name="my_files"),
path("MyFiles/<int:pk>/", views.delete_file, name="delete_file"),
{% extends 'layouts/base.html' %}
{% load static %}
{% block title %} {% endblock title %}
<!-- Specific CSS goes HERE -->
{% block stylesheets %}{% endblock stylesheets %}
{% block content %}
{% include "includes/footer.html" %}
<h2>My Files</h2>
<table class="table">
<thead>
<tr>
<th>File Name</th>
<th>File Description</th>
<th>Uploaded By</th>
<th>Download</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
{% for file in files %}
<tr>
<td> {{ file.File_Name }}</td>
<td> {{ file.File_Type }}</td>
<td> {{ file.Uploaded_By }}</td>
<td>
<a href="{{ file.File.url }}" class="btn btn-primary btn-sm" target="_blank">
Download File
</a>
</td>
<td>
<form method="post" action="{% url 'delete_file' file.pk %}">
{% csrf_token %}
<button type="submit" class="btn btn-dange btn-sm">Delete</button>
</form>
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock content %}
<!-- Specific JS goes HERE -->
{% block javascripts %}
<script>
}
},
},
},
});
</script>
{% endblock javascripts %}
class File(models.Model):
File_Name = models.CharField(max_length=200, null=True)
File_Type = models.CharField(max_length=30, null=True)
Uploaded_By = models.CharField(max_length=90,default=None,blank=True, null=True)
Password = models.CharField(max_length=100, null=True)
File = models.FileField(upload_to='Files')
def __str__(self):
return self.File_Name
def delete(self, *args, **kwargs):
self.File.delete()
super().delete(*args, **kwargs)
def UploadedBy(self,username):
self.File.Uploaded_By = username
# Create your forms here.
class FileForm(forms.ModelForm):
class Meta:
model= File
fields= ["File_Name", "File_Type","Uploaded_By","Password","File"]
You should define a form with a field for entering password which validates against the password of the specific file, then add your delete or download logic after form.is_valid() is called

Django can't upload file

I'm doing a django app with a form using image file upload. I have a default image in case user doesnt choose an image. But when I save the form, my image isn't saved in my files. Any idea ?
Here's my code :
First my views.py
class AnimalCreateView(generic.CreateView):
model = Animal
form_class = AnimalForm
template_name = 'myApp/animal_create.html'
success_url = reverse_lazy('animal:index')
Then my models.py
class Animal(models.Model):
name= models.CharField()
animal_photo= models.ImageField(upload_to="images/",default="images/noPhoto.svg", null=False, blank=True)
def __str__(self):
return f'{self.name}'
And my animal_create html :
{% extends 'base.html' %}
{% load static %}
{% block content %}
<div class="container-fluid">
<div class="row">
<div class="col-lg-8 offset-lg-2">
<h4>My anmials</h4>
<table class="table">
<thead>
<tr>
<th> </th>
<th>Name</th>
<th>Photo</th>
</tr>
</thead>
<tbody>
{% for animal in animal_list%}
<tr>
<td>{{animal.name}}</td>
<p> {{ animal.photo.url }} </p> #check url file
<td class="picture-thumb">
{% if animal.photo.url %}
<img src="{{ animal.photo.url}}"" />
{% else %}
<img src="{% static 'images/noPhoto.svg' %}" />
{% endif %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
{% endblock content %}
When I save my file and then check my html or django admin page, all the rows of animal_photo are using the default file...
Where are you using form from context? And also, to upload an images(files) you need to set
{% if form.is_multipart %}
<form enctype="multipart/form-data" method="post" action="/foo/">
{% else %}
<form method="post" action="/foo/">
{% endif %}
https://docs.djangoproject.com/en/3.1/ref/forms/api/#testing-for-multipart-forms

django form is not validating

So I have been trying to implement a way to post a project post in my website. However, it seems that there is something wrong with my validation with forms. Even if the form is correct and complete, it still wont validate.
No posts are being made in my projects page and nothing gets added in my database. I am not sure what is going on.
I don't see any errors in my terminal.
My code is below:
views.py
class CreateProjectsView(View):
def get(self, request):
p_photos = P_Images.objects.all()
#project_form = ProjectsForm(initial=self.initial)
project_form = ProjectsForm()
context = {
'p_photos': p_photos,
'project_form': project_form,
}
return render(self.request, 'projects/forms.html', context)
def post(self, request):
project_form = ProjectsForm(request.POST or None, request.FILES or None)
p_formset = P_ImageForm(request.POST, request.FILES)
# Checks if the project_form is valid before save
if project_form.is_valid():
instance = project_form.save(commit=False)
instance.user = request.user
instance.save()
# Checks if multiple image upload is valid before save
if p_formset.is_valid():
#if project_form.is_valid() and p_formset.is_valid():
#instance = project_form.save(commit=False)
#instance.user = request.user
#instance.save()
images = p_formset.save(commit=False)
images.save()
data = {
'is_valid': True,
'name': images.p_file.name,
'url': images.p_file.url
}
else:
data = {
'is_valid': False,
}
return JsonResponse(data)
forms.html
{% extends "projects/test.html" %}
{% block javascript %}
<form action="{% url 'create_post:retrieve_projects' %}" method="POST" enctype="multipart/form-data">
{% csrf_token %}
{% for hidden in project_form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% for field in project_form %}
{{ field }} <br />
{% endfor %}
<input type="submit" value="OK">
{% load static %}
{# JQUERY FILE UPLOAD SCRIPTS #}
<script src="{% static 'projects/js/jquery-file-upload/vendor/jquery.ui.widget.js' %}"></script>
<script src="{% static 'projects/js/jquery-file-upload/jquery.iframe-transport.js' %}"></script>
<script src="{% static 'projects/js/jquery-file-upload/jquery.fileupload.js' %}"></script>
{# PHOTOS PAGE SCRIPTS #}
<script src="{% static 'projects/js/basic-upload.js' %}"></script>
{# 1. BUTTON TO TRIGGER THE ACTION #}
<button type="button" class="btn btn-primary js-upload-photos">
<span class="glyphicon glyphicon-cloud-upload"></span> Upload photos
</button>
{# 2. FILE INPUT TO BE USED BY THE PLUG-IN #}
<input id="fileupload" type="file" name="p_file" multiple
style="display: none;"
data-url="{% url 'create_post:create_projects' %}"
data-form-data='{"csrfmiddlewaretoken": "{{ csrf_token }}"}'>
{# 3. TABLE TO DISPLAY THE UPLOADED PHOTOS #}
<table id="gallery" class="table table-bordered">
<thead>
<tr>
<th>Photo</th>
</tr>
</thead>
<tbody>
{% for p_photo in p_photos %}
<tr>
<td>{{ p_photo.file.name }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<h1>hahahaha</h1>
</form>
{% endblock %}
This has been plaguing me for 2 weeks now. Its starting to discourage me from learning django in python :(
Your form action is pointing to create_post:retrieve_projects change it so it points to create_post:create_projects

Newbie - Python Django - NoReverseMatch Error

I have gone through lots of related questions but I am not able to solve this issue so I though I will finally post it, I have an app 'Customers' which will hold a list of customers, currently there are two user levels
1) Customer - If I login as a Customer I would ONLY see my details and I must be able to edit and make changes to my information
2) Advisor - If I login as an Advisor I would see a list of customers and I would be able to make changes to any customer.
To achieve this I have an 'Edit' button when clicked redirects to a 'form' with the particular fields already populated, I can edit and save. Issue arises when I click on this 'Edit' I get this error "NoReverseMatch at /customer/". But when I directly navigate to the form by typing in, "localhost:8000/customer/1/edit" I could see the form.
Here's my views.py
#login_required
def customer_edit(request, cust_number):
# customer = get_object_or_404(Customer, pk=cust_number)
if request.method == "POST":
form = CustomerForm(request.POST)
# form = CustomerForm(request.CUSTOMER, instance=customer)
if form.is_valid():
customer = form.save(commit=False)
customer.cust_number = request.user
customer.updated_date = timezone.now()
customer.save()
return redirect('customer', pk=cust_number)
else:
form = CustomerForm()
return render(request, 'customers/customer_edit.html', {'form': form})
Here's my appname/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^customer/$', views.customer, name='customer'),
url(r'^home/$', views.home, name='home'),
url(r'^customer/(?P<cust_number>\d+)/edit/$', views.customer_edit, name='customer_edit'),
]
Here's a part of my projectname/urls.py
url(r'', include('customers.urls', namespace="customers"))
Here's my customers/forms.py
from django import forms
from .models import Customer
class CustomerForm(forms.ModelForm):
class Meta:
model = Customer
fields = ('cust_number', 'name', 'address', 'city', 'state', 'zipcode', 'email', 'cell_phone',)
Here's my customer_edit.html
{% extends 'customers/base.html' %}
{% block content %}
<h1>Edit Customer</h1>
<form method="POST" class="customer-form">{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-default">Save</button>
</form>
{% endblock %}
Here's my customer.html
{% extends 'customers/base.html' %}
{% block content %}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Eagle Financial</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
</head>
<body>
<style>
body {
background-color: beige;
}
</style>
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="panel panel-primary">
<div class="panel-heading">Welcome!</div>
<div class="panel-body">
Eagle Financial Services, your Midwest Financial Services Partner.
</div>
</div>
</div>
</div>
</div>
<div class="row">
<h2 style="padding-left: 15Px">Customer Information</h2>
</div>
<div>
<table class="table table-striped table-bordered table-hover">
<thead>
<tr class="bg-info">
<th>Customer ID</th>
<th>Name</th>
<th>Address</th>
<th>City</th>
<th>State</th>
<th>Zip</th>
<th>Primary Email</th>
<th>Cell Phone</th>
<th colspan="3">Actions</th>
</tr>
</thead>
<tbody>
{% for customer in customers %}
<tr>
<td>{{ customer.cust_number }}</td>
<td>{{ customer.name }}</td>
<td>{{ customer.address }}</td>
<td>{{ customer.city }}</td>
<td>{{ customer.state }}</td>
<td>{{ customer.zipcode }}</td>
<td>{{ customer.email }}</td>
<td>{{ customer.cell_phone }}</td>
<td>Update</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</body>
</html>
{% endblock %}
Here's my error,
NoReverseMatch at /customer/
Reverse for 'customer_edit' with no arguments not found. 1 pattern(s) tried: ['customer/(?P<cust_number>\\d+)/edit/$']
Request Method: GET
Request URL: http://127.0.0.1:8000/customer/
Django Version: 1.11.1
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'customer_edit' with no arguments not found. 1 pattern(s) tried: ['customer/(?P<cust_number>\\d+)/edit/$']
I have tried trial and errors of namespaces, but not able to solve this. Please guide me. Thanks.
I am using Python - 3.6, Django - 1.11
You are doing wrong in views
customer.cust_number = request.user #Why you assign user to cust_number?
customer.updated_date = timezone.now()
customer.save()
return redirect('customer', pk=cust_number)
Update your view code with below:
from django.core.urlresolvers import reverse
#login_required
def customer_edit(request, cust_number):
# customer = get_object_or_404(Customer, pk=cust_number)
if request.method == "POST":
form = CustomerForm(request.POST)
# form = CustomerForm(request.CUSTOMER, instance=customer)
if form.is_valid():
customer = form.save(commit=False)
customer.cust_number = request.user.pk
customer.updated_date = timezone.now()
customer.save()
return reverse('customers:customer_edit', request.user.pk)
else:
form = CustomerForm()
return render(request, 'customers/customer_edit.html', {'form': form})
Use this in html
<td>Update</td>

Unable to loop form fields in django

In models.py,I created a character type field called "category".After the user enters the category name,it is saved in the database and now I want to display all the category names stored in the database.I created four category names.I can see all four in the database but when displaying it in the UI, I see NONE instead of the category names.
views.py,
def add_cat(request):
form = CatForm(request.POST or None)
context = {"form":form}
if form.is_valid():
instance = form.save(commit=False)
category = form.cleaned_data.get("category")
instance.category = category
instance.save()
messages.add_message(request, messages.INFO, 'Category Added')
return render(request,"add-cat.html",context)
forms.py,
class CatForm(forms.ModelForm):
class Meta:
model = Add_cat
fields = ['category']
My template file,
{% extends "admin-menu.html" %}
{% block content %}
{% load staticfiles %}
<head>
<link rel="stylesheet" href="{% static 'style.css' %}">
</head>
<h2 style="text-align: center;">Add Category</h2>
<form method="POST">
{% csrf_token %}
<table align="center">
{{form.as_table}}
</table>
<input type="submit" value="Add" style="margin-left: 48%;"/>
<input type="reset" value="Cancel"/>
</form>
{% if messages %}
<ul class="messages" style="list-style-type: none;">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
&nbsp
<form id="id1">
{% for field in form %}
<table align="center">
<tr><th>Category Name</th></tr>
<tr><td>{{field.value}}</td></tr>
</table>
{% endfor %}
</form>
{% endblock %}
Try like this
def add_cat(request):
form = CatForm(request.POST or None)
catagories = <model>.objects.all()
context = {"form":form, 'categories':categories}
if form.is_valid():
instance = form.save(commit=False)
category = form.cleaned_data.get("category")
instance.category = category
instance.save()
messages.add_message(request, messages.INFO, 'Category Added')
return render(request,"add-cat.html",context)
In templates
{% for category in categories %}
<table align="center">
<tr><th>Category Name</th></tr>
<tr><td>{{ category }}</td></tr>
</table>
{% endfor %}

Categories