TemplateSyntaxError - python

I'm having problem using {% url %} tag in django template.
LINK
Throwing this error:
Caught NoReverseMatch while rendering: Reverse for 'baza.views.thread' with arguments '('',)' and keyword arguments '{}' not found.
What's weird, it works used like this:
{{ category.last_post.thread.pk }}
returns correct value which is '8', also doesn't throw error when I'm using it like this:
LINK
Above code works fine, and redirects to thread.
my urls.py :
...
(r"^temat/(\d+)/$", "thread"),
...
post model:
class Post(models.Model):
title = models.CharField(max_length=60)
created = models.DateTimeField(auto_now_add=True)
creator = models.ForeignKey(User, blank=True, null=True)
thread = models.ForeignKey(Thread)
body = models.CharField(max_length=10000)
thread view:
def thread(request, pk):
posts = Post.objects.filter(thread=pk).order_by("created")
posts = mk_paginator(request, posts, 20) # ZMIEN TAKZE W get_thread_page
t = Thread.objects.get(pk=pk)
return render_to_response("baza/thread.html", add_csrf(request, posts=posts, pk=pk, title=t.title,
element_pk=t.element.pk, media_url=MEDIA_URL, path = request.path))
category model has "last_post" metod which returns last msg posted in this category.
Could someone help me with this annoying problem?
Regards.
Ps. I'm using Django Version: 1.3.1

The problem is that the value of the next expression category.last_post.thread.pk is None or ''. And no Reverse for 'baza.views.thread' with arguments '('',)'.
Arguments ('',) implies that category.last_post.thread.pk is None or ''

Related

Django 3.0.8 URL/Template/Routing Troubles "No reverse match"

first post so please forgive my ignorance as this is my first django app.
I am trying to create a template that displays all of the information regarding a specific "Ticket" from a list of all open tickets.
Unfortunately I am receiving following message whenever I attempt to add an anchor with a template url tag:
NoReverseMatch at /tickets/tasks/ Reverse for 'order' with arguments
'('',)' not found. 1 pattern(s) tried:
['tickets/order/(?P<ticket_id>[^/]+)/$']
Error message updated. Please see Update below.
And it is ONLY on this one HTML Template.
Below is all of the code I believe will be able to shed some light into the issue:
models.py:
from django.db import models
# Create your models here.
class Ticket(models.Model):
"""A basic support ticket"""
# User ticket title.
ticket_Name = models.CharField(max_length=50)
# When the request was submitted.
ticket_Submitted = models.DateTimeField(auto_now_add=True)
#Ticket Type
ticketTypeChoices=[
('Update', 'Article Edit/Update'),
('Addition', 'New Content/Article Request'),
('Typo', 'Article Typo/Formatting Issue'),
('Issue', 'Website Error/Issue'),
('Other', 'Other'),
]
# Type of ticket (Update, Addition, Typo, Site Issue)
ticket_Type = models.CharField(
max_length=50,
choices=ticketTypeChoices,
default= 'Other'
)
# Users Name
ticket_Contact = models.CharField(max_length=50)
# User Email (for follow up)
ticket_Email = models.EmailField(max_length=254)
# Article URL (if applicable)
ticket_URL = models.CharField(blank=True, max_length=254)
# User description of the issue.
ticket_Description = models.TextField()
#Ticket Status Choices
StatusChoices = [
('Pending', 'Pending'),
('Open', 'Open'),
('Complete', 'Complete'),
('Deferred', 'Deferred'),
('Awaiting Response', 'Awaiting Response'),
]
# Status of the Ticket
ticket_Status = models.CharField(
max_length=50,
choices=StatusChoices,
default= 'Pending'
)
# Comments from HelpDesk Staff
ticket_Comments = models.TextField(blank=True )
#Shows when the ticket was last saved.
ticket_Last_Updated = models.DateTimeField(auto_now=True)
def __str__(self):
"""Return a string representation of the model"""
return self.ticket_Name
views.py:
# Imports Models from the app
from . models import *
# Imports from the Forms List
from . forms import TicketForm
# Create your views here.
# View of all active tickets
def ticket(request):
tickets = Ticket.objects.all().order_by('-ticket_Submitted')
context = {'ticket': tickets}
return render(request, 'tickets/joblist.html', context)
# User can view details about a Ticket
def order(request, ticket_id):
order = Ticket.objects.get(id=ticket_id)
context= {'order': order}
return render(request, 'tickets/tix.html', context)
urls.py
from django.urls import path,include
from . import views
app_name='tickets'
urlpatterns = [
# Include default auth urls.
path('', include('django.contrib.auth.urls')),
# Support Ticket Form
path('submit/', views.submit, name='submit'),
# Contact Us Form
path('contact/', views.contact, name='contact'),
# TicketWeblist
path('tasks/', views.ticket, name='tasks'),
# Ticket Details
path('order/<str:ticket_id>/', views.order, name='order' )
]
Template (joblist.html):
{% for tickets in ticket %}
<tr>
<td>{{tickets.ticket_Name}}</td>
<td>{{tickets.ticket_Type}}</td>
<td>{{tickets.ticket_Contact}}</td>
<td>{{tickets.ticket_Status}}</td>
<td>{{tickets.ticket_Submitted}}</td>
<td>{{tickets.ticket_Last_Updated}}</td>
<td><a class="btn btn-sm btn-info" href="{% url 'tickets:order' ticket.id %}">View</a>
</tr>
{% endfor %}
After reviewing the code a dozen time, all I can be sure of is that is an issue that begins with the template anchor template url tag. (View) but no matter what format I try it comes up with this or a similar error.
UPDATE: At Mel's suggestion changed the url 'order' to 'tickets:order' and am now receiving the following message:
NoReverseMatch at /tickets/tasks/ Reverse for 'order' with arguments
'('',)' not found. 1 pattern(s) tried:
['tickets/order/(?P<ticket_id>[^/]+)/$']
I have been attempting to resolve this issue for about three days and was determined to solve it myself. Any type of help is appreciated and please feel free to point out any spaghetti code or lack of notes as well as I am looking for ways to grow.
Thanks!
You've set a namespace for your urls: app_name = 'tickets'
So correct reverse url would be.
{% url 'tickets:order' tickets.id %}
Can you try changing your order view function to this -
def order(request, ticket_id):
active_order = Ticket.objects.get(id=ticket_id)
context= {'order': active_order}
return render(request, 'tickets/tix.html', context)
You have created a separate urls.py for you app (it looks like it), so be sure to include namespace = tickets in your project urls.py file. And then in your template, you should do as follows:
{% url 'tickets:order' ticket.id %}
In other words, you need to include the name of the app as well.
I just saw that you are passing ticket.id from your template to the view, however there is no ticket.id anywhere in the code. Why don't you try passing a value that is there in the template. It should work.

Django Reverse Error: NoReverseMatch at

Hello StackOverFlow Members, before i get down to the point, let me retrace my thought/process here to help further slim down my issue. When i click a location object in "location_tree.html" it would redirect me to a new page, "location.html", displaying the location name and its type. From the very same page, the name would be a hyperlink to another page with more details about the "location".
Above is the general flow i want, but when i attempt to click the name from location.html, it redirects me to this error:
NoReverseMatch at /accounts/location/2/
Reverse for 'continent' with keyword arguments '{u'pk': 2}' not found. 1 >pattern(s) tried: ['accounts/location/(?>P\d+)/location_continent/(?P\d+)/']
Some key things to note, i am using python2.7. Lastly, when i remove the {% url %} from location.html everything works perfectly fine.
Here is my working code,
App/models.py:
class Location(models.Model):
title = models.CharField(max_length=255)
location_type = models.CharField(max_length=255, choices=LOCATION_TYPES)
parent = models.ForeignKey("Location", null=True, blank=True,
related_name="parent_location")
def __unicode__(self):
return self.title
class Continent(models.Model):
title = models.CharField(max_length=255)
location = models.OneToOneField(Location, on_delete=models.CASCADE, primary_key=True)
is_an_island = models.BooleanField(default=False)
def __unicode__(self):
return self.location.title
App/views.py:
def view_page_location(request, location_id):
location = Location.objects.get(id=location_id)
if location.location_type == 'Continent':
continent = Continent(location=location, is_an_island=False)
return render(request, 'accounts/location.html', {'location':location, 'continent':continent})
def view_continent(request, pk):
get_continent=get_object_or_404(Continent, pk)
return render(request, 'accounts/location_continent.html', {'get_continent':get_continent})
Project/urls.py:
from App.views import *
url(r'^accounts/location/(?P<location_id>\d+)/', view_page_location, name='location'),
url(r'^accounts/location/(?P<location_id>\d+)/location_continent/(?P<pk>\d+)/', view_continent, name='continent'),
Templates,
location_tree.html:
{% for child in locations %}
{% if child.parent == location %}
<ul>
{{ child }}
location.html:
{% if location.location_type == 'Continent' %}
<h2> Location: {{ location.title }}</h2>
<h3> Type: {{ location.location_type }} </h3></br>
location_continent.html:
<p> hello </p>
I left location_continent pretty generic because i wanted to see if i can get it to work. I feel that something is wrong somewhere in my Urls.py or maybe i'm not properly constructing my views.py.
So the BIG question is, what changes/modifications do i need to alter in order to fix that error? I can't see it myself so i turn to 'you'. Any links for me to read up on and find the answer myself is appreciated as well. I hope my question is clear and not vague.
Two issues.
Your continent url in the location.html doesn't provide location_id argument, you provided only pk. Change it to something like:
{{ location.title }}
In the urls.py, you must add $ at the end of the location url, else there is going to be confusion between location and continent urls. $ has a special meaning in regular expression and means that it requires that the pattern matches the end of the string. Change urls to:
url(r'^accounts/location/(?P<location_id>\d+)/$', view_page_location, name='location'),
url(r'^accounts/location/(?P<location_id>\d+)/location_continent/(?P<pk>\d+)/', view_continent, name='continent')

Django 1.6 reverse() fails, kwarg value missing from Exception value

I have an affiliate program app with redirects and link statistics tracking. A read-only field in the Django Admin should display the full URL of the affiliate link, (so the user can copy+paste this into their editor) but the reverse() call in the model instance's get_absolute_url() method is failing when called from a callable in the admin class. For example:
from project urls.py
urlpatterns = patterns(
'',
url(r'^a/', include('shop.affiliates.urls', namespace='affiliates')),
...
from shop.affiliates.urls.py
urlpatterns = patterns(
'',
url(r'^(?P<slug>[\w]+)/$', redirect_to_affiliate_link, name='affiliate_redirect'),
)
from shop.affiliates.models.py
class AffiliateLink(models.Model):
...
slug = models.SlugField(
max_length=4,
help_text='The slug for this link, used to generate url.',
)
...
def get_absolute_url(self):
return reverse(
'affiliates:affiliate_redirect',
kwargs={'slug': self.slug},
)
Note: for the sake of debugging simplicity, it's safe to assume that the slug field has already been populated in the database previously. So I'm not trying to create a new object where slug has not yet been set.
from shop.affiliates.admin.py
class AffiliateLinkInline(admin.StackedInline):
model = AffiliateLink
extra = 0
fields = (
..., 'hyperlink', ...
)
readonly_fields = (
'hyperlink', ...
)
def hyperlink(self, obj):
url = 'http://example.com{}'.format(obj.get_absolute_url())
return '{0}'.format(url)
hyperlink.allow_tags = True
When loading the appropriate admin page, I get a NoReverseMatch exception.
Exception value:
Reverse for 'affiliate_redirect' with arguments '()' and keyword arguments '{u'slug': u''}' not found. 1 pattern(s) tried: [u'a/(?P<slug>[\\w]+)/$']
so the proper regex is found, but the slug parameter is empty. I verified that obj.slug within the admin callable exists, and it is the correct AffiliateLink slug. To make matters more strange, if I switch the kwargs in get_absolute_url() like so:
def get_absolute_url(self):
return reverse(
'affiliates:affiliate_redirect',
kwargs={'bug': self.slug},
)
Then the exception value changes to:
Reverse for 'affiliate_redirect' with arguments '()' and keyword arguments '{u'bug': u'7aeB'}' not found. 1 pattern(s) tried: [u'a/(?P<slug>[\\w]+)/$']
So the kwarg value for key 'slug' disappears from the exception value, but the value for 'bug' stays.
What am I doing wrong here? Any help is greatly appreciated.
URL patterns are sometime evaluated before URLconf has been loaded. Try reverse_lazy instead of reverse
https://docs.djangoproject.com/en/dev/ref/urlresolvers/#reverse-lazy

DoesNotExist error in django view/template with one-to-one field

I have these models.
class Storypak(models.Model):
headline = models.CharField('Headline', max_length=200)
pub_date = models.DateField(blank=True)
class Story(models.Model):
storypak = models.OneToOneField('Storypak', blank=True, null=True)
copy = models.TextField(blank=True)
And this view.
def pak_detail(request, pak_id, year, month, day):
pak = Storypak.objects.get(pk=pak_id)
t = loader.get_template('storypak_detail.html')
c = Context ({
'pak' : pak,
})
return HttpResponse(t.render(c))
When I try to use an if statement in my template, a DoesNotExist error is thrown. The documentation I can find indicates that these errors should be silenced. Shouldn't if pak.story resolve False and not throw an error? What am I missing? I think it may have something to do with the OneToOne relationship, but I can't find anything in the docs dealing with this specifically.
Here is the relevant template code as I remember it. I don't have the file on this computer. I'll fix it later if it isn't correct and possibly post the debug info if that would help.
{% if pak.story %}
<p>{{ pak.story.copy }}</p>
{% endif %}
here is a related bug: https://code.djangoproject.com/ticket/10227
here is the source for the if tag: https://code.djangoproject.com/browser/django/trunk/django/template/defaulttags.py#L267
as you see, the tag's render method does not catch anything but VariableDoesNotExist.
You haven't given enough detail to troubleshoot much past the error here, but the simple error message can only be triggered by one statement in your view, that is...
pak = Storypak.objects.get(pk=pak_id)
The pak_id is either invalid, or your model is malformed and a Storypak with that id doesn't exist. That is the only call to an object that would raise a DoesNotExist error. You can verify it is a valid id by adding raise Exception(str(pak_id)) before this line to see what it is attempting to "get." Verify that record exists in the storypak table.

Adding two IDs to my urls dispatcher

I'm relatively new to python/django. I'm having an issue with sending to IDs through my urls.py.
I am trying to add an admin to a business profile page in my project.
My views.py:
#login_required
def make_admin(request, bus_id, user_id):
user = request.user
u = get_object_or_404(User, pk = user_id)
b = get_object_or_404(Business, pk = bus_id)
b.admin.add(u)
followcount = b.followers.count()
photo = BusinessLogo.objects.all().filter(business_link = bus_id)[:1]
return render_to_response('business/followers.html',
{'user':user, 'b':b, 'followcount':followcount, 'photo':photo, 'u':u}, context_instance=RequestContext(request))
In my template I am trying to pass the bus_id as well as the user_id but I keep getting a syntax error, which I am assuming is related to my urls.
My template:
...
{% if follow in b.admin.all %}
[Remove Admin]
{% else %}
[Make Admin]
{% endif %}
...
My urls.py at the moment:
url(r"^make/(?P<bus_id>\d+)/(?P<user_id>\d+)/$", make_admin, name="make_admin"),
url(r"^remove/(?P<bus_id>\d+)/(?P<user_id>\d+)/$", remove_admin, name="remove_admin"),
I am just having a hard time figuring out how to add the user_id to my urls. The above example does not work.
Thanks everyone,
Steve
EDIT: The error Im presented with is:
Caught NoReverseMatch while rendering: Reverse for 'remove_admin' with arguments '(1L, '')' and keyword arguments '{}' not found.
The only thing i can see that seems wrong is {% if follow in b.admin.all %} there's no follow variable in your context in the code you posted.
If you posted more details of your error, or the stack trace, it would be most helpful.
EDIT: Ok, your error is helpful :)
Caught NoReverseMatch while rendering: Reverse for 'remove_admin' with arguments '(1L, '')' and keyword arguments '{}' not found.
This means that the url reversal function got two arguments 1L and ''.
1L i just the integer 1 as a python long integer, the '' means that you passed in None or a blank string.
Since you called the url reversal in your template with {% url remove_admin b.id u.id %} the second argument is the value of u.id. Check the value of the u variable, it seems to not have a valid id attribute, so it's probably not what you expect (I'd guess it's not a User object at all)
You're not referencing the user object in the way you pass it to the context - you pass it as user, but in the template you use u.id.

Categories

Resources