Problem with linking ID of a task in DJANGO - python

I am working on to do app, and I cannot solve this problem.
The problem is linking the tasks with ID or PK...
i am getting this error:
NoReverseMatch at /
Reverse for 'update_task' with arguments '(1,)' not found. 1 pattern(s) tried: ['update_task/
and it is pointing that error is here (in template):
Update
views.py
def updateTask(request, pk):
task = Task.objects.get(id=pk)
form =TaskForm(instance=task)
context = {'form': form}
return render(request, 'tasks/update_task.html',context)
template
<h3>To Do</h3>
<form action='/' method="POST">
{% csrf_token %}
{{form.title}}
<input type="submit" name="Create Task">
</form>
{% for task in tasks %}
<div class="">
Update
<p>{{task}}</p>
</div>
{% endfor %}
URLS.PY
from django.urls import path
from tasks import views
urlpatterns = [
path('', views.index, name='list'),
path('update_task/<str:pk/', views.updateTask, name='update_task'),
]

this will help you
path('update_task/<str:pk>/',views.updateTask, name='update_task'),

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')

ERROR 404 after submitting a form with POST request

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 %}
...

Reverse for 'details' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['entry\\/(?P<pk>[0-9]+)$']

I have this error:
Reverse for 'details' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['entry\/(?P[0-9]+)$']
On line number 7:
From _calender_entry.html
<div class="calender_entry col-lg-4">
<h2> {{ entry.name }} </h2>
<h4> {{ entry.date }} </h4>
<p>
{{ entry.description }}
</p>
<button onclick="window.location='{% url 'details' pk=entry.id %}'" class="btn btn-primary"> View Details </button>
</div>
This is from my urls.py file:
urlpatterns = [
path('', views.index, name='index'),
path('entry/<int:pk>', views.details, name='details'),
path('admin/', admin.site.urls),
]
And here is method from views.py :
def index(request):
entries = Entry.objects.all()
return render(request, 'myapp/index.html', {'entries' : entries})
def details(request, pk):
entry = Entry.objects.get(id=pk)
return render(request, 'myapp/details.html', {'entry' : entry})
Here is models.py
class Entry(models.Model):
name = models.CharField(max_length=100)
date = models.DateTimeField()
description = models.TextField()
created = models.DateTimeField( auto_now_add = True )
def __str__(self):
return f'{self.name} {self.date}'
The _calender_entry.html is included in index.html file as follows:
{% block content %}
<div class="container">
<div class="row">
{% for entry in entries %}
{% include 'myapp/_calender_entry.html' %}
{% endfor %}
</div>
</div>
Could anyone be able to tell me how could I fix this problem?
now django forces you that each app has its own urls.py.
Create the urls.py file in the myapp/ directory
# myapp/urls.py
from django.urls import path
from myapp import views
urlpatterns = [
path('', views.index, name='index'),
path('entry/<int:pk>/', views.details, name='details'),
]
the urls.py of the project has to be as follows
# calenderproject/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include(('myapp.urls', 'myapp'), namespace='myapp')),
]
use in the template as follows
# myapp/_calender_entry.html
View Details
that's how it works, I've checked
I found the error, delete this code from the template _calender_entry.html
<!-- {% include 'myapp/_calender_entry.html' %} -->
although this commented with html django equal it executes it to comment in the template uses {# {% include 'myapp / _calender_entry.html'%} #} in this way django does not execute it

NoReverseMatch during render

I'm receiving this error:
NoReverseMatch at /comments_page/1/post_comment/
Reverse for 'post_comment' with arguments '('',)' not found. 1 pattern(s) tried: ['comments_page/(?P[0-9]+)/post_comment/$']
My views.py
def post_comment(request, product_id):
host_product = Product.objects.get(pk=product_id)
comment = Comment()
comment.product = host_product
comment.author = request.POST["author"]
comment.comment_text = request.POST["comment"]
comment.save()
return render(request, 'comments_page/detail.html', {"host_product": host_product})
My comments_page\urls.py
from django.conf.urls import url
from . import views
app_name = "comments_page"
urlpatterns = [
# /comments_page/
url(r'^$', views.index, name="index"),
# /comments_page/1/
url(r'^(?P<product_id>[0-9]+)/$', views.detail, name="detail"),
# /comments_page/1/post_comment/
url(r'^(?P<product_id>[0-9]+)/post_comment/$', views.post_comment, name='post_comment'),]
My detail.html
<form action="{% url 'comments_page:post_comment' product.id %}" method="post">
{% csrf_token %}
Name: <input type="text" id="author" name="author">
Comment:
<textarea id="comment" name="comment"></textarea><br>
<input type="submit" value="Post Comment">
I think I've identified the problem as being in the product.id here
{% url 'comments_page:post_comment' product.id %}
in the html page. I've tried formatting this a couple of different ways, but I haven't had any luck. Do note, the comment is going through and the form and it works as far as updating the database and loading the entry on the page goes, but the page is not being redirected. I have to reload it manually. Any help would be appreciated.
The error message shows that the argument you pass to the {% url %} tag does not exist and resolves to an empty string. Your view indeed does not pass in a product variable, only a host_product variable. You need to change the tag accordingly:
{% url 'comments_page:post_comment' host_product.id %}
For those who may wonder, the fix is to change the return function in views.py to this
return render(request, 'comments_page/detail.html', {"product": host_product})
I do not understand why this works, but it does. Any suggestions as to how to clean up my post_comment function would be appreciated. I feel it's overly convoluted by using host_product

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.

Categories

Resources