django form is not validating - python

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

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>

filter posts based on a particular field in django template

I am working on a django application. The application holds a form which when filled will redirect to item_list page where the user can view the item they posted and also delete the item. I want this page to list only the items posted by that particular user who is currently logged in. but right now, this page lists items by every user. I tried adding an if case to the template but this results in displaying none of the posts. what am I doing wrong? this is my code so far
items_list template
{% extends 'base.html' %}
{% load staticfiles %}
{% block title %} items {% endblock title %}
{% block header %}
<link rel="stylesheet" href="{% static 'css/item_list.css' %}">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="{% static 'js/item_list.js' %}"></script>
{% endblock header %}
{% block content %}
<div class="container">
<center><h2>Items</h2></center>
<table class='table table-borderless table-hover'>
<thead>
<tr>
<th>Image</th>
<th>Title</th>
<th>Pattern</th>
<th>Color</th>
<th>Vendor</th>
<th>Upload date</th>
<th>Time</th>
<th></th>
<th></th>
</tr>
</thead>
{% for item in items %}
{% if request.user == item.vendor %}
<tr>
<td>
<img src="{{item.img.url}}" alt="{{item.title}}" style="width:80px;">
</td>
<td>{{item.title}}</td>
<td>{{item.pattern}}</td>
<td>{{item.color}}</td>
<td>{{item.vendor}}</td>
<td>{{item.date}}</td>
<td>{{item.time}}</td>
{% endif %}
<td>
Edit item
</td>
<td>
<button class="btn btn-danger btn-sm" data-toggle="modal" data-target="#myModal" style="width:100px">Delete item</button>
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="card-header"><center><h5 class="modal-title">Are you sure you want to delete this item?</h5></center></div>
<div class="modal-body" style="height:200px">
<center>
<br>
<form method="post" action="{% url 'delete_item' item.pk %}" style="margin-top:10%;">
{% csrf_token %}
<button type='submit' class="btn btn-danger" style="width:200px">Delete item</button>
<button type="button" class="btn btn-outline-primary" data-dismiss="modal" style="width:200px">Cancel</button>
</form>
</center>
</div>
<div class="card-footer text-muted">
<center>Once an item is deleted, It cannot be retrieved</center>
</div>
</div>
</div>
</div>
</td>
I am trying to filter the items based on request.user and item.vendor. But this displays none of the items.
views.py
def upload_item(request):
if request.method == 'POST':
form_des = ItemForm(request.POST, request.FILES)
if form_des.is_valid():
form_des.save()
return redirect('item_list')
else:
form_des = ItemForm()
form_des.fields['vendor'].widget.attrs['value'] = request.user
form_des.fields['vendor'].widget.attrs['readonly'] = True
return render(request, 'upload_item.html', {'form_des': form_des})
def item_list(request):
items = Item.objects.all()
return render(request, 'item_list.html', {'items':items})
under upload_item function in views.py, I have made the vendor field readonly and autofilled to the user posting the item so that it cannot be changed.
What am I doing wrong? Please help me
Thank you
You should do the filtering in your view:
def item_list(request):
items = Item.objects.filter(vendor=request.user)
return render(request, 'item_list.html', {'items':items})

Reading Checkbox in Django

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.

Upload a file, having problems with the url in Django

I'm doing a function to upload a file with a example that I found here on Stack Overflow, everything works fine, the problem is that when I try to access the document by a URL, the click sends me to the app url not the photo url, for example I'm trying to access to this
http://localhost:8000/media/documents/2013/10/01/Desert.jpg
and it should be the image URL
documents/2013/10/01/Desert.jpg
view.py
def list(request):
# Handle file upload
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
print form
if form.is_valid():
newdoc = Document(docfile=request.FILES['docfile'],credencial_miembro=request.POST['credencial_miembro'])
print newdoc
newdoc.save()
# Redirect to the document list after POST
return HttpResponseRedirect(reverse('expmedico.views.list'))
else:
form = DocumentForm() # A empty, unbound form
# Load documents for the list page
documents = Document.objects.all()
# Render list page with the documents and the form
return render_to_response(
'upload.html',
{'documents': documents, 'form': form},
context_instance=RequestContext(request)
)
forms.py
class DocumentForm(forms.Form):
docfile = forms.FileField(
label='Select a file',
help_text='max. 42 megabytes'
)
credencial_miembro=forms.CharField(max_length=20)
model.py
class Document(models.Model):
docfile = models.FileField(upload_to='documents')
credencial_miembro= models.CharField(max_length=20,null=False, blank=False)
ulr
url(r'^list/$', 'expmedico.views.list',name='list'),
Setting.py
MEDIA_ROOT = os.path.join(RUTA_PROYECTO, 'media')
MEDIA_URL = '/media/'
template.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Minimal Django File Upload Example</title>
</head>
<body>
<!-- List of uploaded documents -->
{% if documents %}
<ul>
{% for document in documents %}
<li>{{ document.docfile.name }}</li>
{% endfor %}
</ul>
{% else %}
<p>No documents.</p>
{% endif %}
<!-- Upload form. Note enctype attribute! -->
<form action="{% url list %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<table style="width:150%;">
<div style="text-align:center; font-style: oblique; color: red" >
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}><b>{{ message }}</b></li>
{% endfor %}
</ul>
{% endif %}
</div>
<tr>
<td><label>Fecha:</label></td>
<td>
<output><b>{% now "D d M Y" %}</b></output>
</td>
<td>{{ form.credencial_miembro.errors }}<label>Credencial:</label></td>
<td>{{ form.credencial_miembro }} </td>
</tr>
</table>
<p>{{ form.non_field_errors }}</p>
<p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p>
<p>
{{ form.docfile.errors }}
{{ form.docfile }}
</p>
<p><input type="submit" value="Upload" /></p>
</form>
</body>
</html>
You are accessing a model not an image. Also, this might help:
https://docs.djangoproject.com/en/1.2/howto/static-files/
Please take a look there as i don't see this added to the urls.py you pasted.

Categories