pass argument to view with reverse django - django

I have a view create_rating where after I submit a form I want it to be processed on a view rating_upload and then i want to redirect back to the create_rating view. Cant seem to get it to work, my latest code below. I would think when i click submit on the create-rating page that it should send video_id to rating_upload, and from there I can just send it back to create_rating as an argument. The docs show this too. I tried several things the latest error is what i have shown..
urls:
urlpatterns = [
url(r'^upload', UploadVideo.as_view(), name='upload'),
url(r'^(?P<pk>[0-9]+)/$', VideoView.as_view(), name='videoview'),
url(r'^(?P<video_id>\d+)/create_rating', create_rating, name='create_rating'),
url(r'^(?P<video_id>\d+)/rating_upload', rating_upload, name='rating_upload'),
url(r'^(?P<video_id>\d+)/rating_uploaded', rating_upload, name='rating_upload')
]
views:
def create_rating(request, video_id):
vid = get_object_or_404(Video, pk=video_id)
past_ratings = vid.rating.order_by('date_created')[:5]
template = loader.get_template('create_rating.html')
context = {
'vid': vid, 'past_ratings': past_ratings
}
return HttpResponse(template.render(context, request))
def rating_upload(request, video_id):
template = loader.get_template('rating_upload.html')
rated_video = Video.objects.get(pk=video_id)
context = {
'rated_video': rated_video
}
return HttpResponseRedirect(reverse('create_rating', video_id))
template, create_rating.html:
<p>{{ vid.title }}</p>
<form action="{% url 'rating_upload' vid.pk %}" method="post">
{% csrf_token %}
<input type="text" name="rate_comment">
<input type="submit" value="Rate Video">
Latest error:
Request Method: POST
Request URL: http://127.0.0.1:8000/video/32/rating_uploaded
Django Version: 1.10.5
Python Version: 2.7.10
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'video']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "/Users/RyanHelling/virtualenvs/env1/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner
39. response = get_response(request)
File "/Users/RyanHelling/virtualenvs/env1/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/Users/RyanHelling/virtualenvs/env1/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/RyanHelling/PycharmProjects/flash2/video/views.py" in rating_upload
63. return HttpResponseRedirect(reverse('create_rating', video_id))
Exception Type: TypeError at /video/32/rating_uploaded
Exception Value: an integer is required

Try
return HttpResponseRedirect(reverse('create_rating', args=(video_id,)))
instead of
return HttpResponseRedirect(reverse('create_rating', video_id))
Documentation suggests passing your args as a tuple.

Related

How to fix "File is not a zip file"

I am trying to upload some data representing information about products.
The first row of my excel file represents the id of the product.
The data in the column cells (begin from the 2nd row and then) represent serial numbers.
I can not upload successfully my .xls file , taking back the error File is not a zip file.
my view
def excel_view(request):
if "GET" == request.method:
return render(request, 'excel/excel_form.html', {})
else:
excel_file = request.FILES["excel_file"]
# you may put validations here to check extension or file size
wb = openpyxl.load_workbook(excel_file)
sheet_obj = wb.active
# getting a particular sheet by name out of many sheets
worksheet = wb["Sheet1"]
# print(worksheet)
excel_data = list()
# iterating over the rows and
# getting value from each cell in row
#flag=0
header_list=[] #list to store drug index
input_dict={} #dict to store serial numbers per drug
i = 0 #index of columns
j = 0 #index of rows
for row in worksheet.iter_rows():
....
my template
<title>
Excel file upload and processing
</title>
<body style="margin-top: 30px;margin-left: 30px;">
<h1>Excel file upload and processing</h1>
<form action="{% url 'excel_functionality' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file"
title="Upload excel file"
name="excel_file"
style="border: 1px solid black; padding: 5px;"
required="required">
<p>
<input type="submit"
value="Upload"
style="border: 1px solid green; padding:5px; border-radius: 2px; cursor: pointer;">
</form>
my Traceback
Environment:
Request Method: POST
Request URL: http://example/excel/
Django Version: 1.11.16
Python Version: 2.7.12
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'bootstrap3',
'bootstrap_themes',
'intranet',
'crispy_forms',
'fm',
'dal',
'dal_select2',
'django_crontab',
'django_tables2',
'django_filters']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py" in inner
41. response = get_response(request)
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/var/www/vhosts/intranet.health-nutrition.gr/health_nutrition/intranet/views.py" in excel_view
3355. wb = openpyxl.load_workbook(excel_file)
File "/usr/local/lib/python2.7/dist-packages/openpyxl/reader/excel.py" in load_workbook
174. archive = _validate_archive(filename)
File "/usr/local/lib/python2.7/dist-packages/openpyxl/reader/excel.py" in _validate_archive
124. archive = ZipFile(f, 'r', ZIP_DEFLATED)
File "/usr/lib/python2.7/zipfile.py" in __init__
770. self._RealGetContents()
File "/usr/lib/python2.7/zipfile.py" in _RealGetContents
811. raise BadZipfile, "File is not a zip file"
Exception Type: BadZipfile at /excel/
Exception Value: File is not a zip file
Why this happened, any idea?

MemoryError when passing big QuerySet from Views to Template (Django, PostgreSQL)

I'm building a GIS-related web application, and the way it displays the contents of the database on a map is pretty straightforward: the view collects several (currently 122) GeoJSON files and passes them to the template. The template iterates all of them and displays them (using Leaflet). However, I cannot manage to make it work, as every attempt results in a Memory Error.
The database I'm using is a PostgreSQL one, in case it helps. I'm also using a TextField in the model, is it possible that to be source of the issue?
Any advice will be much appreciated :)
The view:
geodata = GeojsonData.objects.filter(connection = my_con).iterator()
view = "map"
return render(request, "map.html", {'geojsonData': geodata})
The template:
{% for dat in geojsonData %}
{% with dat.name as name %}
{% with dat.geodata as gj %}
{{gj}}
L.geoJSON(name).addTo(map);
{% endwith %}
{% endwith %}
{% endfor %}
The model:
class GeojsonData(models.Model):
name = models.CharField(max_length=2000, unique=True)
connection= models.ForeignKey(Connection, related_name='Connection', default=1)
geodata = models.TextField()
The traceback:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/map/1/
Django Version: 1.11.4
Python Version: 3.6.2
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp.apps.myappConfig']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "C:\Users\Xabi\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\exception.py" in inner
41. response = get_response(request)
File "C:\Users\Xabi\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "C:\Users\Xabi\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Xabi\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
23. return view_func(request, *args, **kwargs)
File "C:\Users\Xabi\Desktop\...\views.py" in mapa
92. return render(request, "map.html", {'geojsonData': geodata})
File "C:\Users\Xabi\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\shortcuts.py" in render
31. return HttpResponse(content, content_type, status)
File "C:\Users\Xabi\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\http\response.py" in __init__
303. self.content = content
File "C:\Users\Xabi\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\http\response.py" in content
336. content = self.make_bytes(value)
File "C:\Users\Xabi\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\http\response.py" in make_bytes
247. return bytes(value.encode(self.charset))
File "C:\Users\Xabi\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\functional.py" in _curried
15. return _curried_func(*(args + moreargs), **dict(kwargs, **morekwargs))
File "C:\Users\Xabi\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\safestring.py" in _proxy_method
107. return SafeBytes(data)
Exception Type: MemoryError at /map/1/
Exception Value:
Not sure if you've already solved your problem. But maybe instead of doing the loop in your template, you can do the loop in python and pass the end result to your template?

regex email validation django

Working on a project for school I know how to do this in flask but learning django. I am trying to make sure that a valid email is entered before it post. If I do not do the if else statement the form goes though but wont validate it. I have the following and the only part not working is the one part with comments but I included the whole views.py incase you see something at top that could be wrong.
views.py
from django.shortcuts import render, redirect
from .models import User
import re
EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+#[a-zA-Z0-9._-]+\.[a-zA-Z]+$')
# Create your views here.
def index(request):
return render(request, "emailvalidation/index.html" )
def create(request):
if request.method == 'POST': #here down
if len(request.form['email']) < 1:
add_message("Invalid Email Address!") #if i take out the if else the form does work
elif not EMAIL_REGEX.match(request.form['email']): #the validation.
add_message("Invalid Email Address!")
else:
User.objects.create(email = request.POST['email'] ) #to here
context ={
"email": User.objects.all(),
}
return render(request, 'emailvalidation/success.html' ,context)
the traceback error
Environment:
Request Method: POST
Request URL: http://localhost:8000/user
Django Version: 1.10.6
Python Version: 2.7.10
Installed Applications:
['apps.emailvalidation',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "C:\Users\dbhol\Desktop\DojoAssignments\Python\myenvirnoments\djangoENv\lib\site-packages\django\core\handlers\exception.py" in inner
42. response = get_response(request)
File "C:\Users\dbhol\Desktop\DojoAssignments\Python\myenvirnoments\djangoENv\lib\site-packages\django\core\handlers\base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "C:\Users\dbhol\Desktop\DojoAssignments\Python\myenvirnoments\djangoENv\lib\site-packages\django\core\handlers\base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\dbhol\Desktop\DojoAssignments\Python\myenvirnoments\django2\emailval\emailval\apps\emailvalidation\views.py" in create
15. if len(request.form['email']) < 1:
Exception Type: AttributeError at /user
Exception Value: 'WSGIRequest' object has no attribute 'form'
request does not have a form attribute. Since you already have if request.method == "POST" - you can safely do the following:
change
request.form['email']
with
request.POST['email']
Ideally, you should be using django forms for handing the validations etc. Django forms have better validation logic, regex validators, etc..

'str' object is not callable - SuccessMessageMixin

I get this error in a project whith SuccessMessageMixin and and not know why. This is my code in view.py.
from django.contrib.messages.views import SuccessMessageMixin
from django.views.generic import CreateView
class CampanaNueva(SuccessMessageMixin, CreateView):
model = Campana
template_name = "licencias_campana_nueva.html"
fields = ['temporada', 'descripcion']
success_message = "a"
And Raise this error on save:
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/licencias/editar/1
Django Version: 1.9.4
Python Version: 3.4.4
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'bootstrap3',
'home',
'widget_tweaks',
'socios',
'equipaciones',
'licencias']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'cc_corbelo.middleware.LoginRequiredMiddleware']
Traceback:
File "C:\Python34\lib\site-packages\django\core\handlers\base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "C:\Python34\lib\site-packages\django\core\handlers\base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python34\lib\site-packages\django\views\generic\base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "C:\Python34\lib\site-packages\django\views\generic\base.py" in dispatch
88. return handler(request, *args, **kwargs)
File "C:\Python34\lib\site-packages\django\views\generic\edit.py" in post
279. return super(BaseUpdateView, self).post(request, *args, **kwargs)
File "C:\Python34\lib\site-packages\django\views\generic\edit.py" in post
222. return self.form_valid(form)
File "C:\Python34\lib\site-packages\django\contrib\messages\views.py" in form_valid
14. messages.success(self.request, success_message)
Exception Type: TypeError at /licencias/editar/1
Exception Value: 'str' object is not callable
I have this function working in another project without problems...
I got exactly this same message when I accidentally used the messages framework incorrectly in the form_valid method of a completely different view in my project.
The correct code should have been:
messages.success(request, "Deactivated product")
But what I had written instead was
messages.success = "Deactivated product"
This code doesn't work, but it doesn't cause an error on the page, either! However, as soon as I submitted a different form that used the SuccessMessageMixin, I would see the 'str' object is not callable error.
(Having a problem on one page cause an error on a completely different page was fun to debug.)

Django Type Error - render to string got multiple values for keyword argument context_instance

I'm new in django and I collect all the static and templates from the admin site to customize. Now I'm trying to render a queryset to the change_list.html from the admin site.
view.py
def person_list(request):
if request.method == 'GET':
qs = Person.objects.all()
return render(request, 'admin/change_list.html', {'app_label': 'clients'}, {'results_list':qs})
else:
return render(request, 'admin/change_list.html')
And I'm getting this type error:
render_to_string() got multiple values for keyword argument 'context_instance'
Here is the full traceback:
Environment:
Request Method: GET
Request URL: http://localhost:8000/clients/persons/
Django Version: 1.5.1
Python Version: 2.7.4
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'equipment',
'workers',
'clients',
'rents',
'bills',
'pays')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
115. response = callback(request, *callback_args, **callback_kwargs)
File "/home/facundo/dev/BLPServicios/blpservicios/clients/views.py" in persona_list
9. return render(request, 'admin/change_list.html', {'app_label': 'clients'}, {'results_list':qs})
File "/usr/local/lib/python2.7/dist-packages/django/shortcuts/__init__.py" in render
53. return HttpResponse(loader.render_to_string(*args, **kwargs),
Exception Type: TypeError at /clients/persons/
Exception Value: render_to_string() got multiple values for keyword argument 'context_instance'
Can you help me solve this? Thanks!
Try send values in one dictionary
{'app_label': 'clients', 'results_list':qs}
i think you are using the admin module to do something it can't... what are you trying to do?
i guess you'd better try to do it without the admin. often customizing it is more painful than implementing the code yourself, because of its complexity!
in particular, the {% result_list cl %} tag you see in the admin tamplate change_list.html (line 91) is not a template varible (that you are trying to pass in the context) but a template custom tag! whatever you want to do, this is the wrong path ;)