ERROR 404 after submitting a form with POST request - python

http://127.0.0.1:8000/tasks works fine but when when I add a task and submit it, I get a 404 thrown at me,
ERROR: Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
admin/
polls/
newyear/
tasks/ [name='index']
tasks/ add [name='add']
The current path, tasks/{ % url 'add' % }, didn't match any
of these
mysite\tasks\urls.py
from django.urls import path,include
from . import views
urlpatterns = [
path("", views.index, name='index'),
path("add", views.add, name='add')]
mysite\mysite\urls.py
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('polls/',include('polls.urls')),
path('newyear/', include('newyear.urls')),
path('tasks/', include('tasks.urls'))]
mysite\tasks\views.py
from django.shortcuts import render
tasks = ["foo", "bar", "baz"]
def index(request):
return render(request, "tasks/index.html", {
"tasks": tasks
})
def add(request):
return render(request, "tasks/add.html")
)
mysite\tasks\templates\tasks\index.html
{% extends "tasks/layout.html" %}
{% block body %}
<h1>
Tasks
</h1>
<ul>
{%for task in tasks%}
<li> {{task}}</li>
{%endfor%}
</ul>
Add a New Task
{% endblock %}
mysite\tasks\templates\tasks\add.html
{% extends "tasks/layout.html" %}
{% block body %}
<h1>
Add Task
</h1>
<form action= "{ % url 'add' % }" method="post">
<input type="text" name="task">
<input type="submit">
</form>
View Tasks
{% endblock %}

Aside from Alexey Popov's answer to fix broken tags with space {% ... %}, also remember to add within your form a csrf token:
<form action= "{% url 'add' %}" method="post">
{% csrf_token %}
...

Related

I keep getting : Reverse for 'delete_entry' with arguments '('',)' not found. 1 pattern(s) tried: ['deleteentry/(?P<input_id>[^/]+)/\\Z']

I am a begginer and tried to look up solutions from other threads to no avail,
Here is my views.py :
#login_required(login_url='/login')
def delete_entry(request, input_id):
input=Diary.objects.get(pk=input_id)
input.delete()
return redirect('home')
Here is my urls.py :
urlpatterns = [
path('', views.welcome, name='welcome'),
path('home', views.home, name='home'),
path('MyEntries/', views.MyEntries, name='entries'),
path('deleteentry/<input_id>/', views.delete_entry, name='delete_entry'),
]
Here is my html code :
<p>Hello, {{user.username}} !</p>
{% for article in articles %}
<p> {{ article.title}}<br>
{{ article.description }} <br>
{{ article.date }}
<div class="card-footer text-muted">
</p>
Delete
</div>
{% endfor %}
{% endblock %}
As the error says, this is because input.id resolves to the empty string, so likely input does not exists, or it has no id.
Likely you should work with article.id, or perhaps even more robust, use article.pk. If you delete items, you need to make a DELETE or POST request, so you can not work with a link, you use a mini-form, so:
<form action="post" method="{% url 'delete_entry' article.pk %}">
{% csrf_token %}
<button type="submit" class="delete">Delete</button>
</form>
The view can be further improved by using get_object_or_404, and restrict the view to only POST and DELETE requests:
from django.shortcuts import get_object_or_404
from django.views.decorators.http import require_http_methods
#login_required(login_url='/login')
#require_http_methods(["DELETE", "POST"])
def delete_entry(request, input_id):
input = get_object_or_404(Diary, pk=input_id)
input.delete()
return redirect('home')

Django: Reverse for 'login' not found. 'login' is not a valid view function or pattern name

I'm working on my project for a course and I'm totally stuck right now.
Login doesn't work. I using class-based views. When I`m logged in, everything works.The Logout View works too.
The error is as follows:
NoReverseMatch at /
Reverse for 'login' not found. 'login' is not a valid view function or pattern name.
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 3.1.6
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'login' not found. 'login' is not a valid view function or pattern name.
Exception Location: /home/aleo/#HOME/.virtualenvs/znajdki/lib/python3.8/site-packages/django/urls/resolvers.py, line 685, in _reverse_with_prefix
Python Executable: /home/aleo/#HOME/.virtualenvs/znajdki/bin/python3
Python Version: 3.8.6
My files:
poszukiwania/urls.py
from django.urls import path
from . import views
from django.contrib.auth import views as auth_views
app_name = 'poszukiwania'
urlpatterns=[
path('<slug:kategoria_slug>/', views.rzeczy_list, name='rzeczy_list_by_category'),
path('<int:year>/<int:month>/<int:day>/<slug:rzecz_slug>/<int:id>', views.rzecz_detail, name='rzecz_detail'),
path('login/', auth_views.LoginView.as_view(), name='login'),
path('logout/', auth_views.LogoutView.as_view(), name='logout'),
path('', views.rzeczy_list, name='rzeczy_list'),
]
znajdki/urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('poszukiwania.urls', namespace='poszukiwania'))
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL)
settings.py
LOGIN_REDIRECT_URL = 'poszukiwania:rzeczy_list'
LOGIN_URL = 'login'
LOGOUT_URL = 'logout'
templates/registration/login.html
{% extends "poszukiwania/base.html" %}
{% load static %}
{% block title %}Logowanie{% endblock %}
{% block content %}
<h1>Logowanie</h1>
{% if form.errors %}
<p>
Nazwa użytkownika lub hasło są nieprawidłowe.
Spróbuj ponownie
</p>
{% else %}
<p>Wypełnij aby się zalogować</p>
{% endif %}
<div class="login-form">
<form action="{% url 'poszukiwania:login' %}" method="post">
{{ form.as_p }}
{% csrf_token %}
<input type="hidden" name="next" value="{{ next }}" />
<p><input type="submit" value="Zaloguj się"></p>
</form>
</div>
{% endblock %}
help me, please

Django-Registration redux password change forwards to index page

I can use the Django-Registration redux to login and register and it works fine except for the password change which forwards to: http://127.0.0.1:8000/?next=/accounts/password/change/ which lands on the homepage.
These are my app urls:
class MyRegistrationView(RegistrationView):
def get_success_url(self,user):
return('/createprofile/')
urlpatterns=[
url(r'^$', views.index, name='index'),
url(r'^city/(?P<city_name_slug>[\w\-]+)/$', views.show_city, name='show_city'),
url(r'^user/(?P<username>[\w\-]+)/$', views.show_profile, name='show_profile'),
url(r'^search/$', views.search, name='search'),
url(r'accounts/register/$', MyRegistrationView.as_view(), name='registraion_register'),
url(r'^accounts/', include('registration.backends.simple.urls')),
url(r'^createprofile/$', views.createprofile, name="createprofile"),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
This is the link the I use to change password:
<p>
forgot your password? Ney bother.
Reset password
</p>
This is the password_change_form.html form stored in the same place as other registration forms:
{% extends 'base.html' %}
{% load i18n %}
{% load crispy_forms_tags %}
{% block content %}
<form method="post" action=".">
{% csrf_token %}
{{ form|crispy }}
<input type="submit" value="{% trans 'Submit' %}" />
</form>
{% endblock %}
This is the result from http://127.0.0.1:8000/accounts/:
EDIT: the above scenario happens when the user is not logged in. When the is logged in this error comes up:
NoReverseMatch at /accounts/password/change/ Reverse for
'auth_password_change_done' with arguments '()' and keyword arguments
'{}' not found. 0 pattern(s) tried: []
The issue turned out that I put this:
url(r'^accounts/', include('registration.backends.default.urls')),
in the app's url.py however, it needed to be in the project's url.py.

Django: URL not recognized? Have no idea what I'm doing wrong

So I'm making an episode tracker for tv shows, currently making the "Add show" form. When I go to localhost:8000/add, it says that that is not found. What could I possibly be doing wrong?
views.py
class ShowCreate(CreateView):
model = Show
fields = ['title', 'description', 'episode', 'season']
index.html
Add
urls.py
url(r'^add/$', views.ShowCreate.as_view(), name='show-add'),
show_form.html
{% extends 'show/base.html' %}
{% block title %}Add Show{% endblock %}
{% block content %}
<form action="" method="post">
{% csrf_token %}
<h1>Add show</h1>
{% include 'show/form-template.html' %}
<button>Submit</button>
</form>
{% endblock %}
form_template.html
{% for field in form %}
<div class="form">
<h3>{{field.label_tag}}</h3>
<div class="field">{{field}}</div>
</div><!--form-->
{% endfor %}
This is everything in urlpatterns
urlpatterns = [
# index
url(r'^$', views.IndexView.as_view(), name='index'),
# show detail
url(r'^(?P<show>[\w.#+-]+)/$', views.ShowDetail.as_view(), name='show-detail'),
# form to add show
url(r'^add/$', views.ShowCreate.as_view(), name='show-add'),
# delete show
# signup
# login
# logout
]
Error message:
Page not found (404)
Request Method: GET
Request URL: http://localhost:8000/add/
Raised by: show.views.ShowDetail
main urls.py
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('show.urls')),
]

Reverse for 'home' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []

The name of my project is 'trydjango19' and I have two apps: 'newsletter' and 'posts'.
The trydjango19/urls.py is:
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^posts/', include("posts.urls", namespace='posts')),
url(r'^', include("newsletter.urls", namespace='newsletter')),]
The newsletter/urls.py is:
urlpatterns = [
url(r'^', 'newsletter.views.home', name='home'),]
The newsletter/view.py is:
def home(request):
title = 'ОСТАВЬТЕ ЗАЯВКУ'
form = SignUpForm(request.POST or None)
context = {
"title": title,
"form": form
}
if form.is_valid():
instance = form.save(commit=False)
full_name = form.cleaned_data.get("full_name")
if not full_name:
full_name = "anonymous"
instance.full_name = full_name
instance.save()
context = {
"title": "Ваша заявка принята!"
}
if request.user.is_authenticated() and request.user.is_staff:
queryset = SignUp.objects.all().order_by('-timestamp')
context = {
"queryset": queryset
}
return render(request, "newsletter/home.html", context)
The newsletter/templates/newsletter/home.html is:
{% extends 'newsletter/base.html' %}
{% load crispy_forms_tags %}
{% load staticfiles %}
{% block head_title %}Welcome | {{ block.super }}{% endblock %}
{% block jumbotron %}
{% if not request.user.is_authenticated %}
<img class="close" onclick="show('none')" src="{% static 'img/close.png' %}">
<p class='lead text-align-center'>{{ title }}</p>
<form method='POST' action=''>{% csrf_token %}
{{ form|crispy }}
<p class='text-align-center'>
<input class='btn btn-primary' type='submit' value='Откликнуться' />
</p>
</form>
</div>
<img src="{% static 'img/pony.png' %}" width='380px' />
... etc.
I tried with urls.py in many ways, with 'namespace' and 'app_name' but I still do not understand how it should run properly
In template /home/pavel/DJANG/django19/src/newsletter/templates/newsletter/home.html, error at line 0
Reverse for 'home' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
I surmising that you used url tag in base.html similar below:
{% url 'home' %}
but in main urls.py file you certained name-space for sub urls.py file that is in newsletter app.
change this url tag to below:
{% url 'newsletter:home' %}
Or remove namespace parameter from url(r'^', include("newsletter.urls", namespace='newsletter')),] line.
Notice:
Is better that set end of home url pattern, but this don't raise exception:
urlpatterns = [
url(r'^$', 'newsletter.views.home', name='home'),]

Categories

Resources