Displaying tables error argument to reversed () must be a sequence [duplicate] - python

This question already has an answer here:
Django tutorial, Getting: TypeError at /admin/ argument to reversed() must be a sequence
(1 answer)
Closed 6 years ago.
I'm developing a little app where I can display all the tables in my database (sqlite3) and, choosing one of them, visualize the data ( I know I can do that with the admin, but I need to se that in the app)
I have in my model.py different models, something like myModel1, myModel2...
In my views.py
def myhomepage(request):
tables_list = connection.introspection.table_names()
return render(request, 'myhomepage.html', { 'tables_list': tables_list})
def detail_table(request, table):
try:
Table_to_View = ContentType.objects.get(app_label="myapp", model=table)
except Table_to_View.DoesNotExist:
raise Http404 ("La tabella non esiste")
context = {'Table_to_View' : Table_to_View }
return render(request, "detail_table.html", context )
and the template myhomepage.html
{#something#}
<title>Lista delle tabelle</title>
<body>
{% if tables_list %}
<ul>
{%for t in tables_list %}
<li> {{table}}</li>
{% endfor %}
</ul>
{% endif %}
this is the urls.py
from django.conf.urls import url
from . import views
urlpatterns = {
url(r'^$', views.myhomepage, name='myhomepage'),
url(r'^(?P<table>.*)/$', views.detail_table, name='detail_table'),
}
but it highlights this
{% url 'detail_table' t %}"
and gives me this error:
argument to reversed () must be a sequence
How can I resolve this?
Thank you.
ps: if there is any more clever way to do this, I accept advise!
[edit] adding the view detail_table and urls.py

You are using {} instead of [] for your urlpatterns.
urlpatterns = [
url(r'^$', views.myhomepage, name='myhomepage'),
url(r'^(?P<table>.*)/$', views.detail_table, name='detail_table'),
]
Square braces not curly.

Related

Views return html from another app in Django

I want to show a data with different feature .. So, there are 2 role where admin have 5 columns on the table. when the teacher only have 4 columns on the table. I change the HTML already but when I return classlist.html on teacherpage views.py .. it return the admin classlist.html that have 5 columns on the table.
Here is my code :
Urls.py (Teacher APP):
from django.urls import path
from teacherpage import views
urlpatterns = [
path('', views.index, name='index'),
path('classlist/', views.classlist, name='classlist'),
]
Views.py (Teacher APP):
def classlist(request):
data = classModel.objects.all()
classlist= {
"classlist" : data
}
return render(request,'classlist.html', classlist)
It is complicated without the actual codes of the project from you, but here is an idea about how you can use the same view and same html file for two different tables. For example, if your user's role is stored in the User model, then you can use this code in classlist.html:
{% if user.is_authenticated %}
{% if user.role == 'admin' %}
<table with five columns>
{% else %}
<table with four columns>
{% endif %}
{% else %}
no table for you
{% endif %}
FYI, you do not need to modify any views or urls to make it work.

How do I fix a reverse error in Django when redirecting?

I am currently working on a website where you can create a shopping list. I am trying to insert items into the shoplist. So things like banana, cake, etc would go into shoplist. I got everything to work. When I create the item, it goes inside the database but when I try to redirect back to the website where I pressed create item, it shows the error
Reverse for 'detail' with keyword arguments '{'pk': 1}' not found. 1 pattern(s) tried: ['shoplist/(?P<item_id>[0-9]+)/$']
Also, when I try to enter my details page, it shows the error
Reverse for 'createitem' with arguments '('',)' not found. 1 pattern(s) tried: ['shoplist/(?P<item_id>[0-9]+)/createitem/$']
I think I did something wrong when making my paths or doing something wrong syntax wise. Nothing I found on the internet is fixing it. Is there a way to fix this problem? Thank you very much!
views.py
def createitem(request, item_id):
if request.method == 'GET':
return render(request, 'shoplist/createitem.html', {'form':ItemForm(), 'id':item_id})
else:
form = ItemForm(request.POST)
itemlist = form.save(commit=False)
itemlist.shoplist = Shoplist.objects.filter(user=request.user, pk=item_id).first()
itemlist.user = request.user
itemlist.save()
return redirect('detail', pk=item_id)
urls.py
from django.contrib import admin
from django.urls import path
from shoplist import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.home, name='home'),
#authentication
path('signup/', views.usersignup, name='usersignup'),
path('logout/', views.userlogout, name='userlogout'),
path('login/', views.userlogin, name='userlogin'),
path('create/', views.createlist, name='createlist'),
path('shoplist/', views.currentshoplist, name='currentshoplist'),
path('shoplist/<int:item_id>/', views.detail, name='detail'),
path('shoplist/<int:item_id>/createitem/', views.createitem, name='createitem'),
]
detail.html
{% extends 'shoplist/base.html' %}
{% block content %}
<h2>{{ error }}</h2>
<h1>{{ shopitems }}</h1>
{% for i in item %}
{{i.item}}
{% endfor %}
<form action="{% url 'createitem' item_id %}" method="POST">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Create Item</button>
</form>
{% endblock %}
You want to redirect to the 'detail' view and the arg required for it is item_id as an int. I think you want redirect('detail', item_id=item_id). However, you probably want to get the created pk from the form... Maybe form.instance.pk? So redirect('detail', item_id=form.instance.pk). It's not clear if that form is for saving the same object type as you're viewing with the 'detail' view.
For the {% url %}, I don't think you can use anything but keyword args. So, {% url 'createitem' item_id=item_id %} if you put item_id into the template context.

Creating hierarchical urls in Django

I'm dabbling in django for the first time and I'm stuck on one single issue and it's driving me crazy. I'm trying to create a set of pages with a hierarchical url like this www.example.com/{state}/{county}. Basically the problem I'm having is that I can get www.example.com/{state}, but I don't know how to use the url system in django to carry the state over to the state/county page. What I end up getting is www.example.com//{county}
urls.py
app_name = 'main'
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^(?P<pk>[A-Z]{2})/$', views.StateView.as_view(), name='state'),
url(r'/(?P<pk>[a-zA-Z]*)/$', views.CountyView.as_view(), name='county'),
]
views.py
def index(request):
return render(request, 'main/index.html', {})
class StateView(generic.ListView):
template_name = 'main/state.html'
context_object_name = 'county_list'
def get_queryset(self):
counties = [ // list of a couple counties for testing purposes]
return counties
class CountyView(generic.ListView):
template_name = 'main/county.html'
context_object_name = 'water_list'
def get_queryset(self):
return WaWestern.objects.filter(water_name__contains='Orange') // hard coded for easy testing
index.html
this file is large so I'll just show an example of one of my state links
<a id="s06" href="CA">
state.html
{% if county_list %}
<ul>
{% for county in county_list %}
<li>{{ county }}</li>
{% endfor %}
</ul>
{% else %}
<p>No counties were found.</p>
{% endif %}
I realize this can all be solved by adding a column in my db for the state but I'm 100% sure this can be solved pretty simply, I'm just not sure how
Your url pattern for county is slightly off:
url(r'^(?P<state_pk>[A-Z]{2})/(?P<county_pk>[a-zA-Z]*)/$', views.CountyView.as_view(), name='county')
Hierarchical URL patterns would work with inclusions. Here, it is not a nested URL structure, so it would not match the county, followed by state unless you have a regex pattern to match that.
Also, note the change of the regex pattern name - you might have to tweak your views and templates accordingly

Django: Reverse for 'detail' with arguments '('',)' and keyword arguments '{}' not found

I'm following the official tutorial to learn Django and using 1.5.
I had this link as part of my index template, which was working fine:
<li>{{ poll.question }}</li>
however, this is hardcoded and the tutorial suggested a better way was to use:
<li>{{ poll.question }}</li>
so that you'll be better of when dealing with huge number of templates and u have to make changes to the url.
Since I made the above change I get the following errors when I run the app:
Exception Type: NoReverseMatch
Exception Value: Reverse for 'detail' with arguments '('',)' and keyword arguments '{}' not found.
My urls.py looks like this:
from django.conf.urls import patterns, url
from polls import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^(?P<poll_id>\d+)/$', views.detail, name='detail'),
url(r'^(?P<poll_id>\d+)/results/$', views.results, name='results'),
url(r'^(?P<poll_id>\d+)/vote/$', views.vote, name='vote'),
)
views.py looks like this:
from django.shortcuts import render, get_object_or_404
from django.http import Http404
from polls.models import Poll
def index(request):
latest_poll_list = Poll.objects.order_by('-pub_date')[:5]
context = {'latest_poll_list': latest_poll_list}
return render(request, 'polls/index.html', context)
def detail(request, poll_id):
poll = get_object_or_404(Poll, pk = poll_id)
return render(request, 'polls/detail.html', {'poll': poll})
my index.html template looks like this:
{% if latest_poll_list %}
<ul>
{% for poll in latest_poll_list %}
<li>{{ poll.question }}</li>
{% endfor %}
</ul>
{% else %}
<p> No polls are available.</p>
{% endif %}
Usually I could easily read where the error is coming from and deal with it but in this case I can't spot the cause of the error hence I'm unable to progress with my study.
Any help will be greatly appreciated.
In your index.html you gave poll_id as an argument, but that's just the name the argument will have within the detail function; it is not defined in your template. The actual value you want to call the function with is probably poll.id.
My mistake was a typo on detail.html:
<form action={% url 'polls:vote' polls.id %}" method="post">
should have been
<form action={% url 'polls:vote' poll.id %}" method="post">
It took a while for me to realise the django traceback page was pointing me to the relevant line of code the whole time. :$
This happened to me when I was reading tutorial. I didn't change poll_id to pk:
url(r'^(?P<poll_id>\d+)/$', views.DetailView.as_view(), name='detail'),
vs
url(r'^(?P<pk>\d+)/$', views.DetailView.as_view(), name='detail'),
I encountered this error when I was using a string as a raw value, rather than surrounding by quotes i.e.
{% url 'my_view' string_val %}
instead of
{% url 'my_view' 'string_val' %}
I struggled with this for a while. Then I noticed I had put poll.id and not Poll.id with a (capital P)
also, in
polls/urls.py
i had spelling error
url(r'^(?P[0-9]+)/$', views.detail, name='details'),
vs the correct code
url(r'^(?P[0-9]+)/$', views.detail, name='detail'),
spent some time looking for the error, so look for proper spelling. lol
The error got sorted out for me after correcting the filter condition in views.py.
snippet of my views.py
def post_share(request, post_id):
post = get_object_or_404(Post, id=post_id, status='Published')
snippet from my models.py
class Post(models.Model):
STATUS_CHOICES=(
('draft','Draft'),
('published','Published'),
)
1st value is stored in the database and the second value is for displaying to the users.
raw data from my mysql DB
+---------------------------------------+-----------+
| title | status |
+---------------------------------------+-----------+
| Revolution 2020 | published |
| harry potter and the sorcerer's stone | published |
| harry potter and the cursed child | draft |
| five point someone | published |
| half girlfriend | draft |
| one night at the call center | published |
| Django by example | published |
+---------------------------------------+-----------+
When I had used "published", I was getting the said error. Once I changed the filter to "Published" it all sorted out.
Be careful with your primary key datatype. In my case, i mistakently used int instead str.
if pk is string,
path('addesm/pending/<str:pk>', views.addesm, name='add ESM')

Django: An Error of Getting Templates

I am a beginner of Django. Now, I have a problem of getting templates. The context of my webpage contains just messy code...
Here is photo/views.py:
from django.template import loader, Context
from django.http import HttpResponse
from final.photo.models import Image, Audio
def List(request):
posts = Image.objects.all()
t = loader.get_template("list.html")
return HttpResponse(t, { 'posts': posts })
Here is photo/urls.py:
from django.conf.urls.defaults import *
from final.photo.views import List
urlpatterns = patterns('',
url(r'^$', List),
)
Here is list.html: (some of the code cannot be seen on the webpage)
<pre>
<title>So Easy! - Scene List</title>
<h1>So Easy! Learn Chinese</h1>
{% block content %}
{% endblock %}
I hope someone can help me solve it! Thanks!
Try changing your view to the following:
def List(request):
posts = Image.objects.all()
context = RequestContext(request, {
'posts': posts,
})
return render_to_response('list.html', context)
Also, check that your settings.py has the following:
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)
Finally, you'll also need to change your list.html template to make use of posts variable you're passing by using {{ posts.some_image_attribute }} in your template.
First of all: which version of django are you using? Django 1.3 added View Classes, which make things a lot easier.
Considering you're still on Django 1.2:
You must set the template folder at settings.py:
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
"/absolute/path/to/your/template/folder",
)
Also you need to add a code snippet inside list.html:
{% block content %}
{% for item in posts %}
{% endfor %}
{% endblock %}
It's advised to create a base.html for your templates. After you do this, add {% extends "base.html" %} as the first line of your list.html
The return line of your view function should be:
return render_to_response('list.html', { 'posts' : posts })

Categories