I'm running a program to create a wikipedia style website using python and the django framework. I'm running into an issue where I have a link to edit the wiki page on the entry pages. When the page tries to render I get the error message in the title of this post. I'm not sure why it's not finding the edit page, I think I might have a typo somewhere but I'm not finding it. Any help here would be greatly appreciated!
URLS.py
urlpatterns = [
path("", views.index, name="index"),
path("error", views.error, name="error"),
path("newPage", views.newPage, name="newPage"),
path("random", views.random, name="random"),
path("edit", views.edit, name="edit"),
path("<str:entry>", views.markdown, name="entry")
]
entry.html
{% block nav %}
<div>
Edit Page
</div>
{% endblock %}
views.py entry function
def edit(request, title):
content = util.get_entry(title)
return render(request, "encyclopedia/newPage.html", {
"title": title,
"content": content
})
Your edit URL needs a parameter to specify the entry in the URL, so:
# ↓ url parameter
path('edit/<str:title>/', views.edit, name='edit'),
If the title can contain a slash, you need to use the <path:…> path converter [Django-doc]:
# ↓ url parameter
path('edit/<path:title>/', views.edit, name='edit'),
Related
I tried to learn django a few day ago and make a simple website use that, but for a reason my dropdown in home page didn't work but in another page it's work properly.
Here my html template for that
<div class="dropdown-menu">
{% for category in links %}
<a class="dropdown-item" href="{{ category.get_url }}">{{category.category_name}}</a>
{% endfor %}
</div>
and here my code for django urls.py
urlpatterns = [
path('', views.store, name='store'),
path('<slug:category_slug>/', views.store, name='product_by_category'),
]
and here my code for links references
def menu_links(request):
links = Category.objects.all()
return dict(links = links)
i don't know why in my home page the dropdown button didn't work but in another page it work. i tried to find on my navbar templates and i think there is no problem there but the dropdown still not working and i tried to find on settings.py(to check installation app) but i did it
views.py
def home(request):
products = Product.objects.all().filter(is_available = True)
context = {
'products' : products,
}
return render(request, 'home.html', context)
anyone have idea where the problem is?
The reason why my dropdown not work in some page is because i'm include header tag in my home.html, even it's already in my base.html template
If someone have similar problem please check your page maybe you make some mistake like me
I'm working on an app that allows the user to create, show and edit an entry. right now i'm working on the editing function. what i'm trying to do is have an edit button (that's actually a form that sends data via hidden inputs) that sends the title of the entry to a view called trans whose sole purpose is redirect to the edit view, the reason i did this is so that when i'm working on the edit view, i can simplify the process where if the request method is GET it shows the page with the form where the user can edit the entry and if it's post the edit view can receive the changes and save them without worrying about the redirecting from the entry's page.
The problem lies in the fact that everytime i click the edit button i get the error:
NoReverseMatch at /wiki/trans
Reverse for 'edit' with keyword arguments '{'title': 'Python'}' not found.
I have checked over and over for any misspellings or issues in urls.py or any problems with the naming but i just can't find the bug. and it's frustrating because i thought that this would be the easiest part of the project.
Below is the relevant code. i would be extremely grateful for anyone who points out what i'm doing wrong. Thank you in Advance.
HTML
<div id="edit">
<form action="{% url 'wiki:trans' %}" method="POST">
{% csrf_token %}
<input type=hidden value={{title}} name="title">
<input type=submit value="Edit">
</form>
</div>
views.py
class EntryForm(forms.Form):
title = forms.CharField(label="Title")
content = forms.CharField(widget=forms.Textarea)
def trans(request):
title = request.POST.get("title")
return redirect("wiki:edit", title=title)
def edit(request, title):
if request.method == "GET":
entry = util.get_entry(title)
return render(request, "encyclopedia/edit.html", {
"form": EntryForm({
"content": entry,
"title": title
})
})
else:
form = EntryForm(request.POST)
if form.is_valid():
title = form.cleaned_data["title"]
content = form.cleaned_data["content"]
util.save_entry(title, content)
return redirect("wiki:title", title=title)
urls.py
app_name = "wiki"
urlpatterns = [
path("", views.index, name="index"),
path("search", views.search, name="search"),
path("new", views.new, name="new"),
path("trans", views.trans, name="trans"),
path("edit", views.edit, name="edit"),
path("random", views.rand, name="random"),
path("<str:title>", views.title, name="title")
]
Try adding a / at the end of each url, like this:
urls.py:
app_name = "wiki"
urlpatterns = [
path("", views.index, name="index"),
path("search/", views.search, name="search"),
path("new/", views.new, name="new"),
path("trans/", views.trans, name="trans"),
path("edit/", views.edit, name="edit"),
path("random/", views.rand, name="random"),
path("<str:title>/", views.title, name="title")
]
Also try using reverse and passing in the title as an arg on your views.py:
return redirect(reverse('wiki:title', args=[title]))
Disclaimer.....this is an assignment!
Can someone tell me why I am getting
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/%7B%20%25%20url%20'detail'%20user%20%25%20%7D
Using the URLconf defined in bobbdjango.urls, Django tried these URL patterns, in this order:
[name='home']
profile [name='profile']
user_detail/<str:user_id> [name='detail']
The current path, { % url 'detail' user % }, didn’t match any of these.
You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
I think its a problem with my URL but I am not seeing source of error. I would just like to click on the link on the home page and move to the user details page. See code below...
My Home page
<body>
{% block content %}
<h1>This is home page</h1>
<div>
<!-- Your profile -->
{% for user in users %}
<a href="{ % url 'detail' user % }">
<h3>{{user.first_name}}</h3>
</a>
{% endfor %}
</div>
{% endblock %}
</body>
My main URL
urlpatterns = [
## path('admin/', admin.site.urls),
path('', include('bobbpets.urls') ),
## path('bobbpets/<int:user.id/>', views.userDetails, name='userDetails'),
]
My app URL
urlpatterns = [
## path('admin/', admin.site.urls),
path('', views.home, name='home'),
path('profile', views.profile, name='profile'),
path('user_detail/<str:user_id>', views.userdetail, name='detail'),
]
My Views
def home(request):
users = User.objects.all()
return render(request, 'home.html', {'users': users})
def userdetail(request,user_id):
user = User.objects.get(id=user_id)
return render(request, 'user_detail.html', {'user': user})
def profile(request):
return render(request, 'profile.html')
My Model
from django.db import models
class User(models.Model):
first_name=models.CharField(max_length=30)
last_name=models.CharField(max_length=30)
email=models.EmailField()
def __str__(self):
return '{} {}'.format(self.first_name, self.last_name)
Your template URL should look like this: <a href="{% url 'detail' user %}
Remove the spaces that you have between your percent signs and parenthesis. That will cause an error.
Try this:
<a href="{ % url 'detail' user.id % }">
but I think you should change
'user_detail/<str:user_id>'
as
'user_detail/<int:user_id>'
thanks for taking a moment to try and help me out. Haven't done much coding in many years, switched careers for some reason.. Decided to play with Django, everything was going fine, and I can't figure out this URL/slug problem. I've got some links, first.
It's explained on their GitHub rep but I can't figure it out. I've also used this handy site and am still in the dark.
I Know its relatively simple, just having a hard time finding up to date code and books, and I've been frustrating myself on it for too long to quit. It's got to be an error with my URL's, I just don't know what though. So, have a laugh at my expense (seriously, you should have heard Linode support when I logged into the wrong account and deleted the wrong server.. they have excellent support!) and help me amuse myself a bit through this pandemic, because I'm mostly playing with stufff as part of a bigger project I started a while before I quit computer science and went into welding..
Basically, add a page to a category. Better looking URL's with slugs, no problem, until I try to access outside of /admin with the slug. I've basically got it text for text, and am getting this:
Using the URLconf defined in first_project.urls, Django tried these URL patterns, in this order:
404
[name='index']
rango/
admin/
category/slug:category_name_slug/ [name='category']
^media/(?P.*)$
The current path, category/useless/, didn't match any of these.
I get that when I try to access localhost/rango/category/category-name-slug, or localhost/category/category-name-slug
Here is my project urls.py
from django.contrib import admin
from django.urls import path
from django.urls import include
from django.conf import settings
from django.conf.urls.static import static
from rango import views
urlpatterns = [
path('', views.index, name='index'),
path('rango/', include('rango.urls')),
path('admin/', admin.site.urls),
path('category/slug:category_name_slug/', views.category, name='category'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
And this is from my app urls.py
from django.urls import path
from rango import views
app_name='rango'
urlpatterns = [
path('', views.index, name='index'),
path('category/slug:category_name_slug/', views.category, name='category'),
]
And a snippet from my index.html file, because I can't get category.html to load anywhere without a 404, I can get the slug name to show up beside the category name, if you're wondering what on earth I'm doing.
{% if categories %}
<ul>
{% for category in categories %}
<li>;{{ category.name }} {{ category.slug }};
</li>
{% endfor %}
</ul>
{% else %}
{% endif %}
and last, my app's views.py
from django.shortcuts import render
from rango.models import Category
from rango.models import Page
def index(request):
category_list = Category.objects.order_by( '-likes' )[:50]
context_dict = { 'categories': category_list }
return render(request, 'rango/index.html', context_dict)
def category(request, category_name_slug):
context_dict = {}
category = Category.objects.get(slug=category_name_slug)
context_dict['category_name'] = category.name
pages = Page.objects.filter(category=category)
context_dict['pages'] = pages
context_dict['category'] = category
except Category.DoesNotExist:
return render(request, 'rango/category.html', context_dict)
I get that when I try to access localhost/rango/category/category-name-slug, or localhost/category/category-name-slug
There is a rendering problem with the Markdown file. If you inspect the raw version [GitHub], you see the real urlpatterns. This needs to use angle brackets (<…>), so:
urlpatterns = [
path('', views.index, name='index'),
path('rango/', include('rango.urls')),
path('admin/', admin.site.urls),
path('category/<slug:category_name_slug>/', views.category, name='category'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
#SanZo- Why are you adding the following urlpattern at two places.
path('category/slug:category_name_slug/', views.category, name='category'),
It should only be inside your app (rango).
I don't understand why you would try this.rango/ admin/ category/slug:category_name_slug/
The simplest thing to do is - if you want to access the category_slug view
then do this 127.0.0.1:8000/rango/category/{slug}/
e.g 127.0.0.1/rango/category/pillow/
I'm trying to add a link to blogDetails.html on the main page, but using the {% url '...' %} template tag is raising a Reverse not found exception.
index.html
O blogu
urls.py
path('blogDetails/', views.BlogDetailsPageView.as_view(), name='blogDetails'),
views.py
class BlogDetailsPageView(TemplateView):
template_name = 'blog/blogDetails.html'
main urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('blog/', include('blog.urls', namespace='blog')),
]
This is the error I get:
Reverse for 'blogDetails' not found. 'blogDetails' is not a valid view function or pattern name.
What on earth is going on here? All help appreciated.
In your urlpatterns you use namespace='blog'. Looking at the django documentation for the {% url %} template tag, it says:
If you’d like to retrieve a namespaced URL, specify the fully qualified name:
{% url 'myapp:view-name' %}
If you add the blog namespace to your templatetag call, it should work:
O blogu