ValueError at /sup/ invalid literal for int() with base 10: '' - django-templates

i'm new on stackoverflow and in django
I know this has been asked before, but for my circumstance, I can't seem to figure out why this is being thrown
When I try to delete a user, I am given this error from my console:
ValueError: invalid literal for int() with base 10: ''
Here is my view.py where that code is located:
class Delete_user(DeleteView):
model = AuthUser
template_name = 'delUser.html'
def get_success_url(self):
return reverse('ListUserAdmin')
the templete :
<form action="{% url 'Sup-User' pk=AuthUser.id %}" method="POST">
{% csrf_token %}
<input type="submit" value="Yes, delete." />
No, cancel.
</form>
and this is the url :
url(r'^sup/(?P<pk>.*)', log.views.Delete_user.as_view(),
name='Sup-User',),

Related

Karate assert - I'm trying to extract a value from HTML

I'm making an API call using karate that gives an HTML response (snippet below). I'm trying to extract the value='HotelTestLondonHotel'. I tried to use the Karate.extract but I couldn't find an example of it anywhere. I know I can use JS for this in some way but I was wondering if there was an easier way?
'''
<input type='hidden' name='security_emerchant_id value='HotelTestLondonHotel'/><input type='hidden' name='XXX_IPGTRXNO_XXX' '''
Here's an example from the Karate unit-tests:
Feature: karate.extract()
Background:
* def text = karate.readAsString('extract.html')
Scenario: extract first regex
* def token = karate.extract(text, 'login_form_token.+value=\\"([^\\"]+)', 1)
* match token == 'secret1'
Scenario: extract all regexes
* def tokens = karate.extractAll(text, 'login_form.?_token.+value=\\"([^\\"]+)', 1)
* match tokens == ['secret1', 'secret2']
And here is the HTML:
<html>
<form name="login_form" method="post" action="/login">
<input type="hidden" id="login_form_token" value="secret1">
</form>
<form name="login_form2" method="post" action="/login">
<input type="hidden" id="login_form2_token" value="secret2">
</form>
</html>

How to add HTML attribute without attribute name using TagBuilder?

I am building a Input tag using TagBuilder. I want to build the input tag like below
<input name="IsOkay" type="checkbox" {% if MyObject.IsOkay == true %} checked="checked" {%endif%} />
Assume that I already have string {% if MyObject.IsOkay == true %} checked="checked" {%endif%} in some variable. (This is a Liquid template)
How do I add this string using TagBuilder?
var tag = new TabBuilder("input");
tag.MergeAttribute("name","IsOkay");
tag.MergeAttribute("type","checkbox");
var str = "{% if MyObject.IsOkay == true %} checked="checked" {%endif%}";
how do I add str into tag since there will not be any attribute name?

Django List from empty models got TypeError: unhashable type: 'list'

Sorry for my poor English, I'm working around several days and I'm blocked, I clean my develop/debug database and after that my code that just didn't work any more.
I'm working for around to understand the reason and how to solve, but no clue. Ask for any path to go to solve this situation and help me.
I know I'm doing something wrong because only did:
./manage.py --fork contractos zero
clean all migrations data on contractos/migrations (except init.py)
./manage.py --fake
./manage.py makemigrations
./manage.py migrate
./manage.py runserver
<code>
my list.py
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.http import Http404
from django.shortcuts import render
# Create your views here.
from contractos.models import Contracto
def list(request):
if not request.user.is_staff and not request.user.is_superuser:
raise Http404
contractos_list = Contracto.objects.all() #.order_by("empresa")
paginator = Paginator(contractos_list, 10) # Show 25 contacts per page
page_request_var = 'lista'
page = request.GET.get(page_request_var)
try:
contractos = paginator.page(page)
except PageNotAnInteger:
#If page is not an integer, deliver first page.
contractos = paginator.page(1)
except EmptyPage:
#If page is out of range (e.g. 9999), deliver last page of results.
contractos = paginator.page(paginator.num_pages)
context = {
"object_list" : contractos,
"title": "Lista de Contractos",
"page_request_var": page_request_var,
}
return render(request, "contractos/list.html", context)
**my list.html**
{% extends "base.html" %}
{% block content %}
<div class="col-sm-9 col-sm-offset-1">
<h1>Contractos {{ title }}</h1>
<div class="row">
{% for obj in object_list %}
<div class="col-sm-6 col-md-4">
<div class="thumbnail">
<div class="caption">
<h3>
<a href='{{ obj.get_absolute_url }}'>{{ obj.empresa }} </a><br />
{% if obj.logo %}
<img src="{{ obj.logo.url }}" class="img-responsive"/>
{% endif %}
<small>criado {{ obj.timestamp|timesince }}</small><br />
<small>alterado em {{ obj.updated|timesince }}</small><br />
</h3>
{{ obj.nfic }} <br/>
{{ obj.descricao|linebreaks|truncatechars:60 }}
<p>...</p>
<p>Detalhes
<!--a href="#" class="btn btn-default" role="button">Button</a--></p>
</div>
</div>
</div>
{% cycle "" "<div class='col-sm-12'><hr/></div></div><div class='row'>" %}
{% endfor %}
</div>
<div class="pagination">
<span class="step-links">
{% if object_list.has_previous %}
Primeira
Anterior
{% endif %}
<span class="current">
{% if object_list.number %}
Pagina {{ object_list.number }} de {{ object_list.paginator.num_pages }}.
{% endif %}
</span>
{% if object_list.has_next %}
Seguinte
Ultima
{% endif %}
</span>
</div>
</div>
{% endblock content %}
**my models.py**
from __future__ import unicode_literals
import uuid
from django.db import models
from django.core.urlresolvers import reverse
STATUS_CHOICES = [
('a', 'Activo'),
('s', 'Suspenso'),
('c', 'Cancelado'),
('t', 'Terminado'),
]
def upload_location(instance, filename):
return "contractos/%s/%s" % (instance.nfic, filename)
# Create your models here.
class Contracto(models.Model):
slug = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
nfic = models.CharField(max_length=15, default='PT000000000', unique=True)
empresa = models.CharField(max_length=128, unique=True)
descricao = models.TextField()
status = models.CharField(max_length=1, choices=STATUS_CHOICES, default='a')
logo = models.ImageField(upload_to=upload_location,
null=True,
blank=True,
width_field="width_field",
height_field="height_field"
)
height_field = models.IntegerField(default=0)
width_field = models.IntegerField(default=0)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
def __str__(self):
return self.empresa
def get_absolute_url(self):
return reverse("contractos:details", kwargs={"uuid": self.slug})
class Meta:
ordering = ["empresa"]
db_table = ["Contractos"]
and the error I got when try rendering list.py are:
**Environment:**
Request Method: GET
Request URL: http://127.0.0.1:8000/contractos/
Django Version: 1.10.4
Python Version: 3.5.1
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'contractos']
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 "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/core/paginator.py" in validate_number
34. number = int(number)
**During handling of the above exception (int() argument must be a string, a bytes-like object or a number, not 'NoneType'), another exception occurred:**
File "/home/gwo/Projects/paas/src/contractos/views/list.py" in list
20. contractos = paginator.page(page)
File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/core/paginator.py" in page
50. number = self.validate_number(number)
File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/core/paginator.py" in validate_number
36. raise PageNotAnInteger('That page number is not an integer')
**During handling of the above exception (That page number is not an integer), another exception occurred:**
File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/core/paginator.py" in count
72. return self.object_list.count()
File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/db/models/query.py" in count
369. return self.query.get_count(using=self.db)
File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/db/models/sql/query.py" in get_count
476. number = obj.get_aggregation(using, ['__count'])['__count']
File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/db/models/sql/query.py" in get_aggregation
457. result = compiler.execute_sql(SINGLE)
File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/db/models/sql/compiler.py" in execute_sql
824. sql, params = self.as_sql()
File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/db/models/sql/compiler.py" in as_sql
369. extra_select, order_by, group_by = self.pre_sql_setup()
File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/db/models/sql/compiler.py" in pre_sql_setup
46. self.setup_query()
File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/db/models/sql/compiler.py" in setup_query
36. self.query.get_initial_alias()
File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/db/models/sql/query.py" in get_initial_alias
879. alias = self.join(BaseTable(self.get_meta().db_table, None))
File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/db/models/sql/query.py" in join
921. alias, _ = self.table_alias(join.table_name, create=True)
File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/db/models/sql/query.py" in table_alias
689. alias_list = self.table_map.get(table_name)
**During handling of the above exception (unhashable type: 'list'), another exception occurred:**
File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner
39. response = get_response(request)
File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/gwo/Projects/paas/src/contractos/views/list.py" in list
23. contractos = paginator.page(1)
File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/core/paginator.py" in page
50. number = self.validate_number(number)
File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/core/paginator.py" in validate_number
39. if number > self.num_pages:
File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/utils/functional.py" in __get__
35. res = instance.__dict__[self.name] = self.func(instance)
File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/core/paginator.py" in num_pages
84. if self.count == 0 and not self.allow_empty_first_page:
File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/utils/functional.py" in __get__
35. res = instance.__dict__[self.name] = self.func(instance)
File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/core/paginator.py" in count
77. return len(self.object_list)
File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/db/models/query.py" in __len__
238. self._fetch_all()
File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/db/models/query.py" in _fetch_all
1087. self._result_cache = list(self.iterator())
File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/db/models/query.py" in __iter__
54. results = compiler.execute_sql()
File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/db/models/sql/compiler.py" in execute_sql
824. sql, params = self.as_sql()
File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/db/models/sql/compiler.py" in as_sql
369. extra_select, order_by, group_by = self.pre_sql_setup()
File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/db/models/sql/compiler.py" in pre_sql_setup
46. self.setup_query()
File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/db/models/sql/compiler.py" in setup_query
36. self.query.get_initial_alias()
File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/db/models/sql/query.py" in get_initial_alias
879. alias = self.join(BaseTable(self.get_meta().db_table, None))
File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/db/models/sql/query.py" in join
921. alias, _ = self.table_alias(join.table_name, create=True)
File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/db/models/sql/query.py" in table_alias
689. alias_list = self.table_map.get(table_name)
**Exception Type: TypeError at /contractos/
Exception Value: unhashable type: 'list'**
</code>
</pre>
So I only clean my data from database to restart populate then again with test information to demonstrated the project to our customer, that as you can imagine I had to cancel!
You can't have a function called list because it's a python keyword. Change that to something else and it will work. Also you should avoid naming your file list etc.

Django - Parameter passed to the template but it can not use in if statement

I try to pass the variable to another page using GET method in django. It is possible for me to do that, but the problem is that the variable that I passed is not available in the if statement. I try to print out the value then it worked fine. Then I try to use it inside if statement then I come to know that it was not working properly. I have no idea regarding that. Can anyone help me? Thank you very much.
This is my views:
def test(request):
Test = Photos.objects.all()
ID = request.GET['id']
Context = {
'ID' : ID,
'test' : Test,
'testing' : 3,
}
return render(request, 'test.html', Context)
def tests(request):
tests = Photos.objects.all()
Context = {
'tests' : tests,
}
return render(request, 'tests.html', Context)
This is my urls.py:
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^$', 'flashapp.views.home'),
url(r'^play$', 'flashapp.views.play'),
url(r'^test$', 'flashapp.views.test'),
url(r'^tests$', 'flashapp.views.tests'),]
In tests.html I have buttons for passing id to test.html using GET method.
This is tests.html:
</head>
<body>
<h1>Welcome to tests pages.....</h1>
{% for i in tests %}
Click For {{ i.id }}<br>
{% endfor %}
</body>
This is test.html:
<html>
<head>
</head>
<body>
<h1>Welcome to Test Page</h1>
<h1>{{ ID }}</h1>
{% for i in test %}
<p>{{ i.id }}..........{{ testing }}.........{{ ID }}</p>
{% if ID == i.id %}
<p>Test</p>
<p>Working....ID = {{ i.id }}</p>
{% else %}
<p>In else</p>
{% endif %}
{% endfor %}
</body>
this is tests.html
this is test.html
I suppose to see the "Working....." but, it gone to else block. I have no idea. Help me please!!!
Thank you very much.
I edited my original answer based on your comment
You are passing a QuerySet as your Test object instead of an object in the first view, so it doesn't have an id property.
When you do this:
def test(request):
Test = Photos.objects.all()
...
You are getting a collection of all the Photos objects into the Test variable, which is not what you want, you only want one instance of Photos. For that kind of queries, you need to use the .get method, that returns a single instance or an exception in case it doesn't find it.
Test = Photos.objects.get(pk=request.GET['id'])
Your code now should look like this:
def test(request):
ID = request.GET['id']
Test = Photos.objects.get(pk=ID)
Context = {
'ID' : ID,
'test' : Test,
'testing' : 3,
}
return render(request, 'test.html', Context)
Now, for completeness' sake, this would fail in case the ID is not on the database, so we can do something like this:
def test(request):
try:
ID = request.GET['id']
Test = Photos.objects.get(pk=ID)
Context = {
'ID' : ID,
'test' : Test,
'testing' : 3,
}
return render(request, 'test.html', Context)
except Photos.DoesNotExist:
raise Http404("No Photo matches the given query.")
Of course, Django has its own shortcuts for these kind of things, so your code can be written like this:
from django.shortcuts import get_object_or_404
def test(request):
#I strongly suggest you don't use uppercase in variable names
id = request.GET['id']
test = get_object_or_404(pk=id)
context = {
'ID' : id,
'test' : test,
'testing' : 3,
}
return render(request, 'test.html', context)

NoReverseMatch at /admin/app/model/ - Admin change_list.html

I don't know why I get this error while trying to reach the admin change_list page of the mymodel model:
NoReverseMatch at /admin/myapp/mymodel/
Reverse for 'myapp_mymodel_change' with arguments '(u'',)' and keyword arguments '{}' not found.
Error during template rendering
In template /usr/local/lib/python2.7/dist-packages/django/contrib/admin/templates/admin/change_list.html, error at line 91
84 <form id="changelist-form" action="" method="post"{% if cl.formset.is_multipart %} enctype="multipart/form-data"{% endif %}>{% csrf_token %}
85 {% if cl.formset %}
86 <div>{{ cl.formset.management_form }}</div>
87 {% endif %}
88
89 {% block result_list %}
90 {% if action_form and actions_on_top and cl.full_result_count %}{% admin_actions %}{% endif %}
91 {% result_list cl %}
92 {% if action_form and actions_on_bottom and cl.full_result_count %}{% admin_actions %}{% endif %}
93 {% endblock %}
94 {% block pagination %}{% pagination cl %}{% endblock %}
95 </form>
The error does not occur on my local runserver(Python 2.7.5, Django 1.5.1), only when deployed on my remote server (Python 2.7.2+, Django 1.5.1). Interestingly enough, only one specific model is affected by this -- I can reach the change_list pages of all the other models without any problems whatsoever. The rest of the admin area works fine as well.
The answers to similar questions regarding the NoReverseMatch error didn't help much because it happens in the admin, not my own code. Does anyone know where to start looking?
EDIT:
I had some customised list_display fields which I now commented out for testing. They seemed to be responsible for the NoReverseMatch error. Now I got another error instead:
AttributeError at /admin/myapp/mymodel/
'NoneType' object has no attribute '_meta'
I then stripped away everything that isn't necessary. This is now my complete admin.py:
from django.contrib import admin
from myproject.myapp.models import *
class MymodelAdmin(admin.ModelAdmin):
list_display = ['email', 'user', 'is_active', 'first_used']
date_hierarchy = 'first_used'
ordering = ['-first_used']
list_filter = ['is_active', 'first_used', 'user']
admin.site.register(Mymodel, MymodelAdmin)
And on my local machine it still works perfectly.
There are some variables which are not getting passed during rendering the template ..
Take your lead by checking the required local variables to be passed as to fulfill the url pattern in url tag ..
I encountered same problem when my foreign key is null while using this script not originally mine on my admin change_list.html.
What it does is to display the column for foreign_key of your model.
from django.forms import MediaDefiningClass
class ModelAdminWithForeignKeyLinksMetaclass(MediaDefiningClass):
def __getattr__(cls, name):
def foreign_key_link(instance, field):
# Please note in Django 1.6
# Model._meta.module_name was renamed to model_name
target = getattr(instance, field)
return u'%s' % (
target._meta.app_label, target._meta.model_name, target.id, unicode(target))
if name[:8] == 'link_to_':
method = partial(foreign_key_link, field=name[8:])
method.__name__ = name[8:]
method.allow_tags = True
setattr(cls, name, method)
return getattr(cls, name)
raise AttributeError
I added a line if target: in filter out those null values.
if target:
return u'%s' % (
target._meta.app_label, target._meta.model_name, target.id, unicode(target))
Script usage:
where carrier,sitename are a foreign key field.
class LatestRsl_v2Admin(admin.ModelAdmin):
__metaclass__ = classmaker(right_metas=(ModelAdminWithForeignKeyLinksMetaclass,))
list_display = ['issued', 'link_to_carrier', ]
search_fields = ['=rslno','=issued','link_to_carrier', 'link_to_sitename']