404 on slug in django - python

I am following a tutorial where they do something like this:
Leave a comment
They use slug. I have not been doing that, but have been referencing an ID. The parts of my code which I think are important to this are:
films/urls.py:
from django.conf.urls import url
from django.urls import path
from . import views
app_name = 'films'
urlpatterns = [
path('', views.index, name='index'),
url(r'^films/<int:film_id>/comment/', views.add_comment, name='add_comment'),
path('films/<int:film_id>/', views.detail, name='detail'),
]
films/views.py
def add_comment(request, film_id):
film = get_object_or_404(Film, pk=film_id)
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit = False)
comment.post = post
comment.save()
return redirect('film:detail',film)
else:
form = CommentForm()
template = 'films/add_comment.html'
context = {'form':form}
return render (request,template,context)
mysite/urls.py:
urlpatterns = [
url(r'^accounts/',include('accounts.urls')),
url(r'^', include('films.urls')),
url(r'^admin/', admin.site.urls),
]
add_comment.html:
{% extends 'base_layout.html' %}
{% block content %}
<div class="create-comment">
<h2>Add Comment</h2>
</div>
{% endblock %}
If I click the link I made which is: Leave a comment
I get this:
And if I manually alter the url to
http://127.0.0.1:8000/films/2/comment/
I get this:
But it looks like url 3 in that list matches what I typed?

you are so close. Just some minor mistakes I believe:
(Final Working Edit)
films/urls.py
urlpatterns = [
path('', views.index, name='index'),
path('<int:film_id>/comment', views.add_comment, name='add_comment'),
path('<int:film_id>', views.detail, name='detail'),
]
mysite/urls.py
urlpatterns = [
url('films/', include('films.urls')),
url('accounts/',include('accounts.urls')),
url('admin/', admin.site.urls),
]
(Working out)
films/urls.py:
app_name = 'films'
urlpatterns = [
url(r'^films/(?P<film_id>\d+)/comment/', views.add_comment, name='add_comment'),
]
Notice: (?P<film_id>\d+) that's how you capture the correct identifier
This is incorrect:
Leave a comment
It should be:
Leave a comment
Notice there is no gap in {%
and we now use the identifier we defined in urls.py above.
Your def add_comment(request, film_id): has me a tad confused, however give my suggestions a shot. Then comment with any issues that occurred and we'll solve this!
EDIT: Ok next mini-errors that might be holding you back
urlpatterns = [
path(r'^$', views.index, name='index'),
path(r'^films/<int:film_id>/comment/$', views.add_comment, name='add_comment'),
path(r'^films/<int:film_id>/$', views.detail, name='detail'),
]
Make all the first arg strings regex strings i.e. 'foo' -> r'foo'
According to the v2 release notes, you need to use path( ) to use your cool <int:film_id> syntax. url() will not do it sadly ☹️
End your regexes with a '$', it means end of string. Prevents matching films/2/comment to films/2/

Related

How to switch HTML page in Python with Django

Template :
<a class="btn btn-primary" href="{% url 'edit' %}">Edit</a>ù
views.py:
def edit(request):
return render(request, "edit.html")
urls.py:
urlpatterns = [
path("", views.index, name="index"),
path("wiki/create", views.create, name="create"),
path("wiki/edit", views.edit, name="edit"),
path("wiki/<str:name>", views.entry, name="entry"),
path("search", views.search, name="search"),
path("save", views.save, name="save"),
path("random", views.random, name="random"),
]
I would like simply to switch from an HTML page on another, but the function gives me this error:
TemplateDoesNotExist at /wiki/edit
edit.html
But the template exist, I created it. I tryed a lot of changes but all of them gives me error. Thank you.
The Application name needs to be referenced in the template name.
Like so:
return render(request, "encyclopedia/edit.html")

Having trouble with exempt url

Hi I am trying to exempt a url in my project so that the user can bypass the middleware and reset their password without being logged in. However the urls I have placed in LOGIN_EXEMPT_URLS don't seem to fix this, instead the link to reset-password redirects the user to account/login.
settings.py:
LOGIN_EXEMPT_URLS = {
r'^account/logout/$',
r'^account/register/$',
r'^account/reset-password$',
r'^account/reset-password/done/$',
r'^account/reset-password/confirm(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,23})/$',
r'^account/reset-password/complete/$',
}
middleware.py:
url_is_exempt = any(url.match(path)for url in EXEMPT_URLS)
if path == reverse('accounts:logout').lstrip('/'):
logout(request)
if request.user.is_authenticated and url_is_exempt:
return redirect(settings.LOGIN_REDIRECT_URL)
elif request.user.is_authenticated or url_is_exempt:
return None
else:
return redirect(settings.LOGIN_URL)
urls.py:
urlpatterns = [
url(r'^$', views.home),
url(r'^login/$', auth_views.LoginView.as_view(template_name='accounts/login.html'), name='login'),
url(r'^logout/$', auth_views.LogoutView.as_view(template_name='accounts/logout.html'), name='logout'),
url(r'^register/$', views.register, name='register'),
url(r'^profile/$', views.view_profile, name='view_profile'),
url(r'^profile/edit/$', views.edit_profile, name='edit_profile'),
url(r'^change-password/$', views.change_password, name='change_password'),
url(r'^reset-password/$',
PasswordResetView.as_view(template_name='accounts/reset_password.html',
success_url=reverse_lazy('accounts:password_reset_done')), name='reset_password'),
url(r'^reset-password/done/$', PasswordResetDoneView.as_view(), name='password_reset_done'),
url(r'^reset-password/confirm(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,23})/$',
PasswordResetConfirmView.as_view(), name='password_reset_confirm'),
url(r'^reset-password/complete/$', PasswordResetCompleteView.as_view(), name='password_reset_complete'),
]
main/urls.py:
urlpatterns = [
path('', views.login_redirect, name='login_redirect'),
path('admin/', admin.site.urls),
path('account/', include('accounts.urls', namespace='accounts')),
]
html: This is in {% else %} (user.is.authenticated)
<ul class="navbar-nav ml-auto">
<li class='nav-item'>
<a class="nav-link" href='{% url 'accounts:reset_password' %}'>Forgotten Password?</a>
Everything in html is properly formatted but I think some of the code is bugging out. Sorry about that
FYI: Register in exempt works!
So whats the problem? thnx
Your exempt regex r'^account/reset-password$' does not have a trailing slash. This is inconsistent with the regex in your URL pattern, r'^reset-password/$', which does have a trailing slash.

Django 1.10: The current URL didn't match any of these

mysite/urls.py
from django.conf.urls import url,include
from django.contrib import admin
from django.contrib.auth import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'', include('blog.urls')),
url(r'^accounts/login/$', views.login, name='login'),
url(r'^accounts/logout/$', views.logout,
name='logout', kwargs={'next_page': '/'}),
]
blog/urls.py
from django.conf.urls import include, url
from . import views
urlpatterns = [
url(r'^$',views.PostListView.as_view(),name='post_list'),
url(r'^about/$',views.AboutView.as_view(),name='about'),
url(r'^post/(?P<pk>\d+)/$', views.PostDetailView.as_view()
,name='post_detail'),
url(r'^post/new/$', views.CreatePostView.as_view(), name='post_new'),
url(r'^post/(?P<pk>\d+)/edit/$', views.PostUpdateView.as_view()
, name='post_edit'),
url(r'^drafts/$', views.DraftListView.as_view()
, name='post_draft_list'),
url(r'^post/(?P<pk>\d+)/remove/$', views.PostDeleteView.as_view()
,name='post_remove'),
url(r'^post/(?P<pk>\d+)/publish/$', views.post_publish
, name='post_publish'),
url(r'^post/(?P<pk>\d+)/comment/$', views.add_comment_to_post
, name='add_comment_to_post'),
url(r'^comment/(?P<pk>\d+)/approve/$', views.comment_approve
, name='comment_approve'),
url(r'^comment/(?P<pk>\d+)/remove/$', views.comment_remove
, name='comment_remove'),
]
The error occurs when I try to edit, remove the post, add a comment or remove comment from the post
I can't access any url from blog/urls.py
and I don't know where the error is coming from.
Error
In your template, you have a link where you have missed out the % in the URL tag. You have something like,
{ url 'post_detail' pk=post.pk }
but it should be:
{% url 'post_detail' pk=post.pk %}
When you click on the invalid link, it takes you to drafts/{url 'post_detail' pk=post.pk}, so you get the 404 error.

Writing my first Django app

I am trying my hand at learning Django and trying out the step-by-step tutorial at https://docs.djangoproject.com/en/2.0/intro/tutorial03/.
I have completed the app (well, till the Part 7) and is working as expected (and has been explained in the tutorial).
The only problem (so far) I am facing is when I am trying to navigate from the "Admin" page to the linked page "VIEW SITE" when I am being presented with "Page not found (404)" error. An image is being attached to make the situation clearer.
The link is pointing to "http://127.0.0.1:8000/" whereas it should be pointing to "http://127.0.0.1:8000/polls/". When I add the missing part of the path (manually) in the address bar the correct page (as expected) is presented.
I have tried to search on this as well as many other forums but could not get the right solution.
I am using Django 2.0.6 and Python 3.6.4 on mac sierra.
Shall be grateful for a lead on this.
Thanks
mysite/urls.py
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('polls/', include('polls.urls')),
path('admin/', admin.site.urls),
]
mysite/polls/urls.py
from django.urls import path
from . import views
app_name = 'polls'
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
path('<int:pk>/', views.DetailView.as_view(), name='detail'),
path('<int:pk>/results/', views.ResultsView.as_view(), name='results'),
path('<int:question_id>/vote/', views.vote, name='vote'),
]
polls/template/polls/index.html
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}" />
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li>{{ question.question_text }}</li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
Error on navigation at VIEW SITE
you should open http://127.0.0.1:8000/polls/
not
http://127.0.0.1:8000/.
If you wanna use http://127.0.0.1:8000/ then your path should be
from django.urls import include, path
urlpatterns = [
path('', include('polls.urls')),
path('admin/', admin.site.urls),
]
It should be like this:
path('', include('polls.urls')),
not like this:
path('polls/', include('polls.urls'))
Because it should be the root url of your website
Here is what I have done (may be not the most elegant solution but works just fine).
I have modified the "mysite/urls.py" file as shown:
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('', include('polls.urls')),
path('polls/', include('polls.urls')),
path('admin/', admin.site.urls),
]
This way I am able to access the "polls" page from both "View Site" link on the Django Admin page (url: "127.0.0.1:8000") as well as from link residing elsewhere (url: "127.0.0.1:8000/polls/").
Thanks for all the help.
PS. Visiting https://docs.djangoproject.com/en/2.0/topics/http/urls/ may be of help to learners like me.

Django how to save model in view

I'm new to Django. I'm having an issue where I can't save my model in the views.py. The concept is to have an input field where a user can type in a name, then using request.POST.get('attribute_name') I can save my model, but it's not working. When I print a list of all the objects in that model there's nothing there, even though I don't get an error message during all of this.
template:
<form id="save_form" method="post" action="{% url 'project_view.views.projectz_save' %}">
{% csrf_token %}
<table>
<tr>
<td>Project Name</td>
<td><input name="projectz_name"/></td>
</tr>
</table>
<input type="submit" value="Save" />
</form>
views.py:
def projectz_save(request):
try:
p = Project(name=request.POST.get('projectz_name'))
p.save()
return redirect('http://www.google.com/')
except:
return redirect('http://www.google.com/')
app urls:
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^$', views.register, name='register'),
url(r'^$', views.projectz_save, name='project_save'),
)
site urls:
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^project_view/', include('project_view.urls')),
I even put in some silly redirect code to google.com just to see if the views.py was even executing, but it's not working, though like I said there are no error messages, the page just refreshes. I'm sure I'm doing wrong that's easy to fix, but I'm a noobie. :D
Ok I think maybe I spotted the problem. The view is not executing because you have defined three urls with the exact regex in your project urls.py:
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^$', views.register, name='register'),
url(r'^$', views.projectz_save, name='project_save'),
)
Django match it's urls by iterating over the patterns in the way they appeared so in that file all urls will match index. That's probably the reason why the page appears to be refreshing. Try to modify this a little:
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^register$', views.register, name='register'),
url(r'^save$', views.projectz_save, name='project_save'),
)
This way you can execute the projectz_save method in the views.py if the action of the form matches the url regex.
Hope this helps!

Categories