Getting this error:
Reverse for 'step' with arguments '()' and keyword arguments '{'course_pk': 2, 'step_pk': ''}' not found. 1 pattern(s) tried: ['courses/(?P<course_pk>\\d+)/(?P<step_pk>\\d+)/']
/urls.py
...
url(r'^courses/', include('courses.urls', namespace='courses')),
...
/courses/urls.py
...
url(r'(?P<course_pk>\d+)/(?P<step_pk>\d+)/$', views.step_detail, name='step'),
...
Error during template rendering:
The html line generating the error is:
...
{{ step.title }}
...
courses/models.py
class Course(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=255)
description = models.TextField()
def __str__(self):
return self.title
class Step(models.Model):
title = models.CharField(max_length=255)
description = models.TextField()
content = models.TextField(blank=True, default='')
order = models.IntegerField(default=0)
course = models.ForeignKey(Course)
class Meta:
ordering = ['order', ]
def __str__(self):
return self.title
courses/views.py
def course_detail(request, pk):
# course = Course.objects.get(pk=pk)
course = get_object_or_404(Course, pk=pk)
return render(request, "courses/course_detail.html", {"course": course})
def step_detail(request, course_pk, step_pk):
step = get_object_or_404(Step, course_id=course_pk, pk=step_pk)
return render(request, "courses/step_detail.html", {"step": step})
I can't seem to understand where the problem is as I'm currently new to Django. Much help would be appreciated.
you need
{% url 'courses:step' course_pk=step.course.pk step_pk=step.pk %}
step.pk instead of step_pk which doesnot exist in your context
In the line
<a href=" {% url 'courses:step' course_pk=step.course.pk step_pk=step_pk %} ">
Here step_pk = step_pk is not working. Step_pk is not defined because you did not return any information about step_pk in def course_detail at this line:
return render(request, "courses/course_detail.html", {"course": course})
pass step inside return and use step_pk = step.pk
Please check it. Thanks.
Related
views.py
def download(request, wallpaper_name):
try:
wallpaper = Wallpaper.objects.get(name=wallpaper_name)
similar_wallpapers = wallpaper.tags.similar_objects()[:2]
except Exception as exc:
wallpaper = None
similar_wallpapers = None
messages.error = (request, 'Sorry! data does not exist')
context = {'wallpaper': wallpaper, 'similar_wallpapers': similar_wallpapers}
return render(request, 'Wallpaper/download.html', context)
models.py
class Tags(models.Model):
tag = models.CharField(max_length=100)
def __str__(self):
return self.tag
class Wallpaper(models.Model):
name = models.CharField(max_length=100, null=True)
size = models.CharField(max_length=50, null=True)
pub_date = models.DateField('date published', null=True)
resolution = models.CharField(max_length=100, null=True)
category = models.ManyToManyField(Category)
tags = TaggableManager()
Device_Choices = [
('PC', 'pc'),
('mobile', 'mobile')
]
Devices = models.CharField(max_length=20,choices=Device_Choices, default= 'PC')
image = models.ImageField(upload_to='Wallpaper/Images/', default="")
def __str__(self):
return self.name
download.html
<div class="tag">
<h3>Tags</h3>
<ul>
<li>{{wallpaper.tags}}</li>
</ul>
</div>
I want all the tags of that particular wallpaper to be rendered
and if possible please tell me if there is any other way to handle tags, because using taggit its very difficult i am getting manny errors
Tags are a many-to-many relation so you need to use .all in your template to get them. However, this will just show you the queryset, so you need to loop through them to render their names:
<ul>
{% for tag in wallpaper.tags.all %}
<li>{{ tag.name }}</li>
{% endfor %}
</ul>
I am getting this error:
TypeError at /product/177042279214449276022367789942330057699/
product() got an unexpected keyword argument 'id'
I am trying to generate detail page of product (book is product).
urls.py
app_name = 'bookrepo'
urlpatterns = [
path('',views.home,name='home'),
path('product/',views.product,name='product'),
path('product/<id>/', views.product, name='product_detail'),
]
template where I am using get_absoulte_url
<a href="{{ item.get_absolute_url }}" class="btn btn-sm my-btn detail-btn">
<span><i class="fa fa-info-circle"></i></span> View Details
</a>
views.py
def product(request):
return render(request, 'bookrepo/product.html')
models.py
class Book(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
title = models.CharField('Title', max_length=255)
authors = models.ManyToManyField(Author, related_name='books_written')
publisher = models.ForeignKey(Publisher, on_delete=models.DO_NOTHING, related_name='books_published')
price = models.DecimalField('Price', decimal_places=2, max_digits=10)
description = models.TextField('Description')
upload_timestamp = models.DateTimeField('Uploading DateTime', auto_now_add=True)
categories = models.ManyToManyField(Category, related_name='book_category')
def get_absolute_url(self):
return "/product/%i/" % self.id
I might be completely wrong with respect to my view and urls. I want to display book details after button in template gets clicked.
Change views.py
def product(request, id=None):
return render(request, 'bookrepo/product.html')
I get a TypeError when I use the following code in my Django Template:
{% for signature in petition.get_signatures %}
{% include 'petition/signature.html' with petition=petition %}
{% endfor %}
Here are my models and classes:
class Petition(models.Model):
title = models.CharField(max_length= 90, default="Enter petition title here")
created_on = models.DateTimeField(auto_now_add=True)
image = models.ImageField(null=False, upload_to='static/petition-photos/%Y/%m/%d')
video = models.CharField(max_length=600, default="Enter an external video link")
petition = models.TextField(null=False, default="Type your petition here")
created_by = models.ForeignKey(User)
def total_likes(self):
return self.like_set.count()
def __str__(self):
return self.title[:50]
def get_signatures(self):
return self.signature_set.all
class Signature(models.Model):
petition= models.ForeignKey(Petition)
user = models.ForeignKey(User)
description = models.TextField(null=False, blank=False)
anonymous = models.BooleanField()
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.petition
I get the following error message when I load my template view page with the 'for' condition. The error message I get is 'method' object is not iterable. What might I be doing wrong? Any solutions? I'm kind of a noob so if you could explain the solution too, that would be great.
You need to call the .all() method:
def get_signatures(self):
return self.signature_set.all()
You returned the method object itself, rather than the result it produces when called, and the {% for signature in .. loop tries to iterate over that method object, and can't.
Im reviewing a sample DJango code and trying to understand how the urls are resolved?
list.html
Categories
{% for c in active_categories %}
{{c.name}}<br />
{% endfor %}
urls.py
from django.conf.urls import *
urlpatterns = patterns('ecomstore.catalog.views',
(r'^$','index',{'template_name':'catalog/index.html'},'catalog_home'),
(r'^category/(?P<category_slug>[-\w]+)/$','show_category',{'template_name':'catalog/category.html'},'catalog_category'),
(r'^product/(?P<product_slug>[-\w]+)/$','show_product',{'template_name':'catalog/product.html'},'catalog_product'),
)
The above html list all the categories without any problem and its called when I enter the following in the browser..[http:127.0.0.1:8000]
When I hover over - a href="{{p.get_absolute_url}} - I get the url resolved to--[http://127.0.0.1:8000/category/electronics/]
The p.get_absolute_url is resolved only to electronics but Im wondering how "category" is resolved in the url..
models.py
class Category(models.Model):
name = models.CharField(max_length=50)
slug = models.SlugField(max_length=50,unique=True,help_text='Unique value for product page URL created from name')
description = models.TextField()
is_active = models.BooleanField(default=True)
meta_keywords = models.CharField("Meta Keywords",max_length=255,help_text="comma-delimited set of SEO Keywords for meta tag")
meta_description = models.CharField("Meta description",max_length=255,help_text="Content for description meta tag")
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now_add=True)
class Meta:
db_table = 'categories'
ordering = ['-created_at']
verbose_name_plural = 'Categories'
def __unicode__(self):
return self.name
#models.permalink
def get_absolute_url(self):
return ('catalog_category',(),{'category_slug':self.slug})
Hope my question is clear...
get_absolute_url is a function defined inside the model (for example, Category) model like this:
class Category(models.Model):
name = models.CharField(max_length=200)
...
def get_absolute_url(self):
return "/category/%s/" % self.slug
It is also possible to use reverse function to resolve the url using a pattern defined in urls.py:
def get_absolute_url(self):
return reverse('catalog_category', args=[str(self.slug)])
which is almost equal to an old-fashioned form:
#models.permalink
def get_absolute_url(self):
return ('catalog_category', (), {'category_slug': str(self.slug)})
In both ways, calling the get_absolute_url method on a Category object, for example Category(name="electronics"), will result in the string: /category/electronics/.
As you can see in your urls.py, the second url pattern is named catalog_category, which appeard in the reverse function argument. When you call the reverse function, Django will look into urls.py files, looking for a pattern named catalog_category, and the final url will be generated by replacing the url parameter (category_slug) with self.slug.
So, I'm working on a bar tab application in Django, and when it came down to insert some data into the tabs I'm getting the error:
ValueError at /tabs/345/add/Caipirinha/
invalid literal for int() with base 10: '345/add/Caipirinha'
I have tried some of the solutions provided before on Stackoverflow but with no success.
Here are some of my files:
models.py
class Tab(models.Model):
number = models.IntegerField()
name = models.CharField(max_length='50')
tabdate = models.DateTimeField('date created')
consumed = models.ManyToManyField(Product, through='ConsumedRelation')
def __unicode__(self):
return self.name
class ConsumedRelation(models.Model):
tab = models.ForeignKey(Tab)
product = models.ForeignKey(Product)
count = models.PositiveIntegerField(blank=True, null=True, default=1)
def __unicode__(self):
return str(self.tab) + " | " + str(self.count) + " " + str(self.product)
views.py
def addproduct(request, tabnumber, product):
tabnumber = Tab.objects.get(number=number)
productadd = Product.objects.get(name=str(product))
add = ConsumedRelation.objects.create(product=productadd, tab=tabnumber, count=1)
add.save()
context = {'tabnumber': tabnumber, 'product': productadd}
return render_to_response('addproduct.html', context, context_instance=RequestContext(request))
addproduct.html
{% for product in productlist %}
<a href="add/{{ product }}/"<li>{{ product }}</li></a>
{% endfor %}
urls.py
url(r'^tabs/add/(?P<tabnumber>\d)/(?P<product>\d)/$', 'barcomandas.views.addproduct'),
I appreciate the help!
You should be using {% url %} in your template so that Django generates the proper URL.
<a href="{% url 'barcomandas.views.addproduct' tabnumber=sometabnumber product=product %}"<li>{{ product }}</li></a>