post_details() got an unexpected keyword argument 'string' in Django? - python

urls.py :
urlpatterns = [
path('', views.posts, name='home'),
path('<string:slug>', views.post_details, name='detail'),
]
views.py (function) :
def post_details(request, slug):
posts = Posts.objects.get(pk=slug)
return render(request, 'posts/post_details.html', {'posts': posts})
NOTE : I am currently learning django.

Your parameter is called slug, not string.
path('<slug:slug>',...

Related

NoReverseMatch at /blog/redirect2

I'm new to django and I've been trying to test the URLs redirection methods I've tried two options but the return render() keeps giving me this error of no reverse match
this is my urls.py code :
app_name = 'blog'
urlpatterns = [
# path('about', views.about, name = 'about'),
path('about.html', views.about, name='about'),
path('home.html', views.home, name='home'),
# path('home', views.home, name ="home")
path('redirect', views.redirect_view),
path('redirection_fct',views.redirection_fct, name='redir_fct'),
#redirection par la fonction as_view
path('redirect1', RedirectView.as_view(url='http://127.0.0.1:8000/blog/redirection_fct')),
path('redirect2', views.redirect_view1),
]
and this is my views file :
def about(request):
return render(request, 'about.html', {})
def home(request):
return render(request, 'home.html', {})
#redirection par HttpResponseRedirect
def redirect_view(request):
return HttpResponseRedirect("redirection_fct")
def redirect_view1(request):
return redirect('redir_fct')
def redirection_fct(request):
return render(request, 'redirection.html', {})
Is there something wrong with my URLs pattern or it is the render one?
Is this the urls.py on your app? How do you include it on your project urls.py, if you have a namespace for it, then you probably need something like:
def redirect_view1(request):
return redirect('blog:redir_fct')
You can try running from a django shell:
from django.urls import get_resolver
print(get_resolver().reverse_dict.keys())

Django base.models.Post.DoesNotExist

I am very new to django. I have followed the steps from a video on youtube on how to create a simple blog. Basically, I have a portfolio main page that displays several things including the latest blogs. It all works well. I can see the latest posts on the main page. I can also click in each of them and they open up fine.
However, now, I want to create a new page (blog.html) that will hold all the posts. I created a blog.html and did the necessary settings in views.py and urls.py. However, for some reason I get an error when trying to access localhost/blog/
This is my urls.py:
urlpatterns = [
path('', views.home, name='home'),
path('work/', views.work, name='work'),
path('<slug:slug>/', views.post_detail, name='post_detail'),
path('blog/', views.blog, name='blog'),
]
Here views.py:
def home(request):
posts = Post.objects.all()
return render(request, 'home.html', {'posts': posts})
def post_detail(request, slug):
post = Post.objects.get(slug=slug)
return render(request, 'post_detail.html', {'post': post})
def blog(request):
posts = Post.objects.all()
return render(request, 'blog.html', {'posts': posts})
This happens if you trigger the post_detail view with a slug, and no Post with that slug exists. But here you simply trigger the wrong view. This is because <slug:slug>/ will also match blog/, so you will never trigger the blog/ view. You should reorder the views, so:
urlpatterns = [
path('', views.home, name='home'),
path('work/', views.work, name='work'),
# before <slug:slug>
path('blog/', views.blog, name='blog'),
path('<slug:slug>/', views.post_detail, name='post_detail'),
]
It might however be better to make non-overlapping patterns, since now if you ever make a Post with blog as slug, that post is inacessible. You thus might want to rewrite the path to:
urlpatterns = [
path('', views.home, name='home'),
path('work/', views.work, name='work'),
path('blog/', views.blog, name='blog'),
# non-overlapping patterns
path('post/<slug:slug>/', views.post_detail, name='post_detail'),
]
Note: It is often better to use get_object_or_404(…) [Django-doc],
then to use .get(…) [Django-doc] directly. In case the object does not exists,
for example because the user altered the URL themselves, the get_object_or_404(…) will result in returning a HTTP 404 Not Found response, whereas using
.get(…) will result in a HTTP 500 Server Error.

How to write urlpatterns in django?

I have this structure of urls:
page/section/subsection/article, where section, subsection and article are user-generated slug names.
How can I write the urlpatterns?
I do this, but may be exist better method?
urlpatterns = [
url(r'^$', views.index),
url(r'^(?P<slug>[-\w]+)/$', views.section),
url(r'^(?P<slug>[-\w]+)/(?P<subslug>[-\w]+)/$', views.subsection),
url(r'^(?P<slug>[-\w]+)/(?P<subslug>[-\w]+)/(?P<articleslug>[-\w]+)/$', views.article)
]
My views:
def index(request):
return render(request, 'MotherBeeApp/index.html', {})
def section(request, slug):
sections = Section.objects.filter(page=slug)
if sections:
return render(request, 'MotherBeeApp/section.html', {'Sections': sections})
else:
return render(request, 'MotherBeeApp/404.html', status=404)
def subsection(request, slug, subslug):
subsection = Section.objects.get(link_title=subslug)
articles = Article.objects.filter(section=subsection.pk)
page_title = subsection.title
return render(request, 'MotherBeeApp/subsection.html', {'Articles': articles, 'PageTitle': page_title})
def article(request, slug, subslug, articleslug):
article = Article.objects.get(link_title=articleslug)
return render(request, 'MotherBeeApp/article.html', {'Article': article})
If you are using Django version older than Django 2.0 (< 2.0) than you are doing right thing and you are already using optimistic way. but if your Django version is later than or equals to Django 2.0 you could write urlpatterns as shown here.
Maybe you can upgrade your Django to 2.0+, and then use code as follows:
from django.urls import path, include
urlpatterns = [
path('', views.index),
path('<slug:slug>/', include([
path('', views.section),
path('<slug:subslug>/', views.subsection),
path('<slug:subslug>/<articleslug>/', views.article),
])),
]

Django doesn't render the requested view

people. I'm a beginner Django developer so sorry if it's a basic question.
I have a webpage that shows a list of movies and each movie has a details view, but for some reason, the details view is never rendered.
#views.py
def index(request):
latest_movies = Movie.objects.order_by('-movie_id')[:5]
template = loader.get_template('ytsmirror/index.html')
context = {
'latest_movies' : latest_movies,
}
return HttpResponse(template.render(context, request))
def detail(request, movie_id):
movie = Movie.objects.get(movie_id=movie_id)
template = loader.get_template('ytsmirror/details.html')
context = {
'movie' : movie,
'plot': 'Lorem impsum',
}
return HttpResponse(template.render(context, request))
And my urls.py
#urls.py
from django.conf.urls import url
from . import views
app_name = 'ytsmirror'
urlpatterns = [
url(r'$', views.index, name='index'),
url(r'^(?P<movie_id>\d{4})$', views.detail, name='detail'),
]
When I try to reach /ytsmirror/4200/ for example, I don't get any error and Django apparently reaches the correct URL pattern but doesn't render the details view, it stays on the index view, without any change.
What am I doing wrong? Thanks.
url(r'$', views.index, name='index') matches the end of the string, so basically it will match any url, that's why your code isn't working. You need to replace url(r'$', views.index, name='index') with url(r'^$', views.index, name='index') so that it will match only empty url
^ asserts position at start of the string
$ asserts position at the end of the string, or before the line terminator right at the end of the string (if any)

Django generic view is not accepting arguments

I am new to Django and I am just trying to pass arguments to Django generic base View and it is not showing up in terminal as I am printing the arguments passed.
views.py
from django.views.generic import View
class CartView(View):
def get(self, request, *args, **kwargs):
item = request.GET.get('item')
qty = request.GET.get('qty')
print item, qty
return HttpResponseRedirect('/')
urls.py:
urlpatterns = [
url(r'^home/$', 'newsletter.views.home', name='home'),
url(r'^contact/$', 'newsletter.views.contact', name='contact'),
url(r'^about/$', 'dressika.views.about', name='about'),
url(r'^admin/', include(admin.site.urls)),
url(r'^accounts/', include('registration.backends.default.urls')),
url(r'^', include('products.urls')),
url(r'^categories/', include('products.urls_categories')),
url(r'^cart/', CartView.as_view(), name='cart'),
When I add some data in browser like "localhost:8000/cart/?item=2&qty=5" it is not showing the arguments in terminal according to above code. By only typing "localhost:8000/cart/" it does redirects me to homepage. But with arguments it shows 404.
It sounds like you may have to fix the entry in urls.py routing to the view. Could you post your urls.py as well?

Categories