Reverse match not found in Django - django

I broke something. The error reads: Reverse for 'wiki_article_detail' with arguments '(u'',)' and keyword arguments '{}' not found. I don't know where the 'u' came from in arguments. here is the model:
class Article(models.Model):
"""Represents a wiki article"""
title = models.CharField(max_length=100)
slug = models.SlugField(max_length=50, unique=True)
text = models.TextField()
author = models.ForeignKey(User)
is_published = models.BooleanField(default=False, verbose_name="Publish?")
created_on = models.DateTimeField(auto_now_add=True)
objects = models.Manager()
published = PublishedArticlesManager()
country = models.CharField(max_length=100)
category = models.CharField(max_length=100)
def __unicode__(self):
return self.title
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.title)
super(Article, self).save(*args, **kwargs)
#models.permalink
def get_absolute_url(self):
return ('wiki_article_detail', (), { 'slug': self.slug })
The template is:
<body>
{% if object_list %}
<h2 class="articlePageTitle">All Articles</h2>
<h3>Filter by country</h3>
<h3>Filter by category</h3>
<ul>
{% for article in object_list %}
<li>
{{ article.title }}
</li>
{% endfor %}
</ul>
{% else %}
<h2>No articles have been published yet.</h2>
{% endif %}
<a href="{% url wiki_article_add %}">Create new article</a
</body>
the debugger is indicating the error in this line:
{{ article.title }}
This was all working fine before, I had some db problems and had to recreate the db file, but there wasn't much in there. But now, I can write an article and view it, but I can't get to the /all list.
urls.py snippet:
url(r'^all/$',
'django.views.generic.list_detail.object_list',
{
'queryset': Article.published.all(),
},
name='wiki_article_index'),
the urls.py snippet that is referenced in the error:
url(r'^article/(?P<slug>[-\w]+)$',
'django.views.generic.list_detail.object_detail',
{
'queryset': Article.objects.all(),
},
name='wiki_article_detail'),

Try this one:
{{ article.title }}

Related

All the users name who liked a post in django

I cannot show all the users name who liked the post in django. I have tried many ways to do that but its not working.
my models.py:
class post(models.Model):
title = models.CharField(max_length=100)
image = models.ImageField(upload_to='post_pics', null=True, blank=True)
video = models.FileField(upload_to='post_videos', null=True, blank=True)
content = models.TextField()
likes = models.ManyToManyField(User, related_name='likes', blank=True)
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
def delete(self, *args, **kwargs):
self.image.delete()
super().delete(*args, **kwargs)
def get_absolute_url(self):
return reverse ('blog-home')
in views.py :
def like_post(request):
# posts = get_object_or_404(Post, id=request.POST.get('post_id'))
posts = get_object_or_404(post, id=request.POST.get('post_id'))
is_liked = False
if posts.likes.filter(id=request.user.id).exists():
posts.likes.remove(request.user)
is_liked = False
else:
posts.likes.add(request.user)
is_liked = True
return render(request, 'blog/home.html')
def post_likes(request, pk):
posts = get_object_or_404(post, pk=pk)
post_likes = posts.likes.all()
context = {'post_likes': post_likes,}
return render(request, 'blog/post_likes.html', context)
in urls.py:
path('post/<int:pk>/postlikes/', views.post_likes, name='post-likes'),
and in post_like.html:
{% extends "blog/base.html" %}
{% block content %}
{% for likes in posts %}
<p>{{ posts.likes.user.all }}</p>
{% endfor %}
{% endblock content %}
How can i see the usernames who liked the particular post?
You iterate over the post_likes, which are User objects, and then you render the user.username:
{% extends "blog/base.html" %}
{% block content %}
{% for user in post_likes %}
<p>{{ user.username }}</p>
{% endfor %}
{% endblock content %}
Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

Django complex QuerySet ManyToManyField with other ManyToManyField

Sorry for this title, I wasn't sure how to name it properly. I'm having problem with getting queryset of ManyToManyField that is in relation with other ManyToManyField. So it's look like this, there is model Company that has ManyToManyField with Person and Person model got ManyToManyField with Position, because logic behind it is that 1 company can have many persons and 1 person can have few positions and can be employed by few companies (which is clear I think). I'm getting the queryset for Person in Company by this way
{% for team in brand.team.all %}
<p>{{ team.first_name }} {{ team.last_name }}</p>
<img class="img-thumbnail" src="/media/{{ team.photo }}">
<p>{{ team.position }} </p>
<p>{{ team.about }} </p>
{% endfor %}
And I'm getting what I want, comparing this to template looks like this
but I'm not getting positions of person, only company.Position.None and I've no idea how to get this. From documentation so far I know that it works for single ManyToManyField but I couldn't find example similar to mine case and I'm not sure how I should get (person's position)
Below are my files
models.py
from django.db import models
...
TYPES = (
('Startup', 'Startup'),
... )
CITIES = (
('Warszawa', 'Warszawa'),
... )
STACK = (
('PHP', 'PHP'),
... )
STUDENTS = (
('No', 'No'),
('Yes', 'Yes')
)
STACK_ICONS = (
('/static/icons/stack/php.png', 'PHP'),
('/static/icons/stack/javascript.png', 'JavaScript'),
...
)
POSITIONS = (
('CEO', 'Chief Executive Officer'),
('CTO', 'Chief Technology Officer'),
...
)
# object position with relationship many to many to person
class Position(models.Model):
position = models.CharField(max_length=50, choices=POSITIONS)
def __str__(self):
return self.position
# object person relation many to one (many persons to one company)
class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
about = models.TextField(max_length=500, default=None)
position = models.ManyToManyField('Position')
photo = models.ImageField(blank=True, null=True, default=None)
def __str__(self):
return "%s %s" % (self.first_name, self.last_name)
# object company
class Company(models.Model):
# field person with relation many to one (many persons to 1 company)
team = models.ManyToManyField('Person')
name = models.CharField(max_length=100, blank=False)
technologies = models.ManyToManyField('Stack')
website = models.TextField(max_length=150, blank=True, null=True, validators=[URLValidator()])
...
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
super(Company, self).save(*args, **kwargs)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.name
# object stack relation manytomany with Company
class Stack(models.Model):
name = models.CharField(max_length=30, choices=STACK)
icon = models.CharField(max_length=80, choices=STACK_ICONS)
def __str__(self):
return self.name
views.py
from django.shortcuts import render, get_object_or_404, redirect
...
def brands(request, slug):
brand = get_object_or_404(Company, slug=slug)
return render(request, 'company/comp_view.html', {'brand': brand})
def stacks(request):
stack = get_object_or_404(Stack)
return render(request, 'company/comp_view.html', {'stack': stack})
def positions(request):
position = get_object_or_404(Position)
return render(request, 'company/comp_view.html', {'position': position})
...
comp_view.html
{% extends 'company/base.html' %}
<div class="col col-md-1"></div>
<div class="col col-md-5 card-section">
<div class="team ">
<div class="card-title">
<span>Team</span>
</div>
<div class="row text-center">
<div class="col col-md-4">
{% for team in brand.team.all %}
<p>{{ team.first_name }} {{ team.last_name }}</p>
<img class="img-thumbnail" src="/media/{{ team.photo }}">
<p>{{ team.position }}</p>
<p>{{ team.about }} </p>
</div>
{% endfor %}
</div>
</div>
{% endblock %}
There's no such thing as a "single ManyToManyField". You have an m2m relationship, you need to iterate through it just like you do for the team members.
{% for position in team.position.all %}
{{ position.name }}
{% endfor %}

form.is_valid() always returns false in views.py

form.is_valid() always fails. I tried different ways to handle it but fails every time and it returns false. Please help in figuring out whats wrong with the code.
models.py looks like this -
class Album(models.Model):
album_name = models.CharField(max_length=50, primary_key=True)
place = models.CharField(max_length=50)
date_pub = models.DateTimeField('date published')
def __str__(self):
return self.album_name
class Images(models.Model):
album_name = models.ForeignKey(Album, db_column='album_name')
image_name = models.CharField(max_length=40)
image = models.FileField(null=True, blank=True)
upload_dt = models.DateTimeField(auto_now=True, auto_now_add=False)
like_cntr = models.IntegerField(default=0)
description = models.CharField(max_length=200, null=True)
def __str__(self):
return self.image_name
forms.py is -
class ImagesForm(forms.ModelForm):
description = forms.CharField(required=False)
class Meta:
model = Images
fields = ('album_name', 'description',)
views.py is -
class RandomView(TemplateView):
template_name = 'photos/random.html'
def get(self, request, album_name):
images = Images.objects.filter(album_name=album_name)
context = {'album_name':album_name, 'images' : images}
return render(request, 'photos/random.html', context)
def post(self, request, album_name):
form = ImagesForm(request.POST)
if form.is_valid():
form.save(commit=False)
text = form.cleaned_data['description']
Images.album_name = album_name
form.save()
else:
return HttpResponse("Failed to save")
Templates is -
<h3>Album : {{album_name }}</h3>
{% for image in images %}
<img src="{{image.image.url}}" height="400" width="500">
<h4> {{image.image_name }}</h4>
<form method="POST" action=""> {% csrf_token %}
<span class = "badge">Description</span>
{% if image.description %}
<h4> {{image.description }} </h4>
{% else %}
<input type="text" value=" "/>
<button type="Submit">Submit</button>
{% endif %}
</form>
{% endfor %}
Where is your necessary name and id attributes for your input tag?
<input type="text" name="description" id="id_description"/>
Please try with {{ form.errors }} above "form" tag. And first of all check that what the errors arrive. Then Find the solution based on that error. Let me know if it is helpful or not.

Problems with extending the polls application

I added an additional Model to the polls application (see django tutorial) which is intended to be a parent for a set of questions:
models.py
class Section(models.Model):
section_text = models.CharField(max_length=255)
section_description = models.TextField(blank=False)
slug = models.SlugField(unique=True, null=True)
def __unicode__(self):
return self.section_text
def save(self, *args, **kwargs):
self.slug = slugify(self.section_text)
super(Section, self).save(*args, **kwargs)
class Question(models.Model):
section = models.ForeignKey(Section)
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __unicode__(self):
return self.question_text
This works fine in the admin. Each question is linked to one section.
Displaying the sections is no problem either:
views.py
class UmfrageView(ListView):
model = Section
context_object_name = 'latest_section_list'
template_name = 'umfrage.html'
But if I want to pass a section via slug to DetailView it doesn't work (if I use generic.ListView instead, it displays questions from all sections):
urls.py
url(
regex=r'^(?P<slug>[-\w]+)/$',
view=DetailView.as_view(),
name='detail'
),
views.py
class DetailView(ListView):
model = Question
context_object_name = 'latest_question_list'
template_name = 'detail.html'
detail.html
{% if latest_question_list%}
{% for question in latest_question_list %}
<p>{{ question.question_text }}</p>
{% for choice in question.choice_set.all %}
<input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
<label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br />
{% endfor %}
{% endfor %}
{% endif %}
If I use generic.DetailView
class DetailView(DetailView):
[...]
the following error shows up:
"Cannot resolve keyword u'slug' into field. Choices are: choice, id, pub_date, question_text, section"
How do I get the set of questions from one particular section and still have an human-friendly URL via slug?
Thanks!
(If further code is required, I'm more than happy to update)
In your DetailView add method get_queryset() to return only required objects as below
class DetailView(ListView):
model = Question
context_object_name = 'latest_question_list'
template_name = 'detail.html'
def get_queryset(self, **kwargs):
slug = self.kwargs.get('slug') or kwargs.get('slug')
if slug:
return Question.objects.filter(section__slug=slug)
else:
return Question.objects.all()

Django NoReverseMatch and Blank Page

I am using Django 1.4.5.
I get an error when I access the detail of entry via admin's page.
"NoReverseMatch at /admin/r/12/1/": Reverse for 'detail' with
arguments '()' and keyword arguments '{'category': u'category',
'slug': u'entry-test'}' not found
And get nothing/blank page when access the detail of entry on front's page (/category/entry-test/).
And what's the right of models & URLname pattern if I want to access the entry detail via sub-category (/category/subcategory/entry-test/)?
Model snippet:
class Entry (models.Model):
title = models.CharField()
slug = models.SlugField()
category = models.ForeignKey('entry.Category')
def __unicode__(self):
return self.title
#models.permalink
def get_absolute_url(self):
return ('entry.views.detail', (), {'category': self.category.slug, 'slug': self.slug})
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.title)
return super(Entry, self).save(*args, **kwargs)
class Category(models.Model):
title = models.CharField()
slug = models.SlugField()
parent = models.ForeignKey('self', blank=True, null=True, related_name='children')
def __unicode__(self):
if self.parent:
return self.parent.title, self.title
return self.title
#permalink
def get_absolute_url(self):
return ('entry.views.category', (), {'slug': self.slug})
Views snippet:
def category(request):
category = Category.objects.all()
return render_to_response('category.html', locals(), context_instance=RequestContext(request))
def list(request, slug_id):
category = get_object_or_404(Category, slug=slug_id)
list = Entry.objects.filter(category=category)
return render_to_response("list.html", locals(), context_instance=RequestContext(request))
def detail(request, category_id, slug_id):
entry = Entry.objects.filter(slug=slug_id)
category = Category.objects.filter(slug=category_id)
return render_to_response('detail.html', locals(), context_instance=RequestContext(request))
URLs snippet:
urlpatterns = patterns('entry.views',
(r'^$', 'category', name='entry-category'),
url(r'^(?P<slug_id>[-\w]+)/$', 'list', name='entry-list'),
url(r'^(?P<category_id>[-\w]+)/(?P<slug_id>[-\w]+)/$', 'detail', name='entry-detail'),
Template snippet:
category.html
<ul>
{% for category in category %}
<li>{{ category.title }} ({{ category.entry_set.all.count }})</li>
{% endfor %}
</ul>
list.html
<ul>
{% for entry in list %}
<li>{{ entry.title }}</li>
{% endfor %}
</ul>
detail.html
<ul>
{% for entry in entry.category %}
<li>{{ entry.title }}
<br />{{ entry.description }}</li>
{% endfor %}
</ul>
Where and what I could be doing wrong?
If any one can help I'd appreciate it! Please help me.
Your keyword arguments for the url are category_id and slug_id, but you are passing in category and slug in your get_absolute_url method. This version should work:
#models.permalink
def get_absolute_url(self):
return ('entry.views.detail',
(), {'category_id': self.category.slug, 'slug_id': self.slug})
Also consider renaming your arguments. id is generally numeric and slug is alphanumeric.
For your blank page problem (from your comment):
Your URL /category/entry-test/ - this will map to your detail view if the snippet your pasted in your question is in your main urls.py. If you have no matching results (the .filter() call has no results), you'll see a "blank" page, because the <ul> will not have any li elements.
If in your main urls.py, you have something like url('^category/', include(some.other.urls)), then the URL will map to your list view, and you have the same issue - the .filter() is not returning any results, and hence you see a "blank" page.
I do little mistake on detail template:
<ul>
{% for entry in entry %}
<li>
{{ entry.title }}
<br />
{{ entry.description }}
</li>
{% endfor %}
</ul>
The problem is solved now.