NoReverseMatch at /Raccourcisseur/ - python

Reverse for 'redirection' with arguments '('',)' not found. 1 pattern(s) tried['Raccourcisseur/Lien/(?P[^/]+)/$']
[About errors][1]
#urls.py#
from django.urls import path
from . import views
urlpatterns = [
path('', views.liste,name='liste'),
path('nouveau/',views.afficher,name='afficher'),
path('Lien/<str:code>/',views.redirection,name='redirection'),
]
#urls.py(global)#
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('Raccourcisseur/',include('mini_url.urls')),
]
#views.py#
from django.shortcuts import render,redirect,get_object_or_404
from .models import MiniURL
from .forms import MiniURLForm
def afficher(request):
if request.method == "POST":
form = MiniURLForm(request.POST)
if form.is_valid():
form.save()
return redirect(liste)
else:
form = MiniURLForm()
return render(request,'mini_url/index.html',{'form':form})
def liste(request):
minis = MiniURL.objects.order_by('-acces')
return render(request, 'mini_url/liste.html', locals())
def redirection(request,code):
""" Redirection vers l'URL enregistrée """
mini = get_object_or_404(MiniURL, code=code)
mini.acces += 1
mini.save()
return redirect(mini.url, permanent=True)
#index.html#
{% extends 'mini_url/base.html' %}
{% block title %}
RaccourcisseurUrl
{% endblock%}
{% block body %}
<h1>Raccourcir une URL </h1>
<form method="post" action="{% url 'afficher' %}">
{% csrf_token %}
{{form.as_p}}
<input type="submit"/>
</form>
{% endblock %}
#liste.html#
{% extends 'mini_url/base.html' %}
{% block title %}
Page RaccourcisseurUrl
{% endblock%}
{% block body %}
<h1>Le raccourcisseur d'URL spécial </h1>
<p></p>Raccourcir une url </p>
<p>Liste des URLs raccourcies : </p>
<ul>
{% for mini in minis %}
<li>{{ mini.url }} via <a href="http://{{ request.get_host }}{% url 'redirection' mini.code %}">
{{ request.get_host } {% url 'redirection' mini.code %} </a>
{% if mini.pseudo %}
par {{ mini.pseudo }}
{% endif %} ({{mini.acces }} accès)
</li>
{% empty %}
<li> Il n'y en pas actuellement </li>
{% endfor %}
</ul>
{% endblock %}

In your list.html most certainly in {% url 'redirection' mini.code %} mini.code has no value.

Related

How to render to template with dropdownbox in django?

I'm a beginner Django. And I got a problem with rendering to the template.
I have a model(models.py) which has the class "FuelInfo"; includes ForeignKey.
from django.db import models
class Traveler(models.Model):
traveler_name = models.CharField(max_length=10)
def __str__(self):
return self.traveler_name
class FuelInfo(models.Model):
name = models.ForeignKey(Traveler, on_delete=models.SET_NULL, null=True)
car = models.CharField(null=True, max_length=50)
efficiency = models.FloatField()
def __str__(self):
return str(self.name)
Also views.py is like :
from django.shortcuts import render, get_object_or_404
from .models import FuelInfo
def traveler_list(request):
travelers = FuelInfo.objects.all()
context = {'travelers':travelers}
return render(request, 'fuelcost/home.html', context)
def traveler_detail(request, pk):
traveler = get_object_or_404(FuelInfo, pk=pk)
return render(request, 'fuelcost/calfuel.html', {'traveler': traveler})
And urls.py is :
from django.urls import path
from . import views
app_name = 'fuelcost'
urlpatterns = [
path('', views.traveler_list, name='home'),
path('<int:pk>/', views.traveler_detail, name='calfuel'),
]
I want to make a dropdown that is render to template "calfuel.html" in home.html.
So I made a template("home.html") like :
{% extends "base_generic.html" %}
{% block content %}
<body>
{% if travelers %}
<form method="POST" action="{% url 'fuelcost:calfuel' pk=traveler.pk %}">
{% csrf_token %}
<select name="traveler">
{% for traveler in travelers %}
<option value="{{ traveler.id }}">{{ traveler.name }}</option>
{% endfor %}
</select>
<input type="submit" value="Select" />
</form>
{% else %}
<p>No travelers are available</p>
{% endif %}
</body>
{% endblock %}
But it doesn't works and i received error.
(My urlpattern is fuelcost/.)
Actually I can go into fuelcost/1 or fuelcost/2 that is views.traveler_detail named "calfuel". But I can't go into fuelcost/ that is views.traveler_list named "home".
I don't know what I have to do more. plz, tell me what is wrong with this.
{% block content %}
<body>
{% if travelers %}
{% for traveler in travelers %}
<form method="POST" action="{% url 'fuelcost:calfuel' pk=traveler.pk %}">
{% csrf_token %}
<select name="traveler">
<option value="{{ traveler.id }}">{{ traveler.name }}</option>
</select>
<input type="submit" value="Select" />
</form>
{% endfor %}
{% else %}
<p>No travelers are available</p>
{% endif %}
</body>
{% endblock %}
you have to keep the form inside loop so that it can get pk of traveler

I do not understand this Django error

Error during template rendering
In template
C:\Users\Paddy\Desktop\Django-tut\mysite\blog\templates\blog\post_list.html,
error at line 10 Reverse for 'post_detail' with arguments '()' and
keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried:
['blog/post/(?P[0-9]+)/$']
{% extends 'blog/base.html' %}
{% block content %}
<div class="post">
{% if post.published_date %}
<div class="date">
{{ post.published_date }}
</div>
{% endif %}
<h1>{{ post.title }}</h1>
<!--<h1>{{ post.title }}</h1>-->
<p>{{ post.text|linebreaks }}</p>
</div>
{% endblock %}
My post_detail.html file looks like this
{% extends 'blog/base.html' %}
{% block content %}
<div class="post">
{% if post.published_date %}
<div class="date">
{{ post.published_date }}
</div>
{% endif %}
<h1>{{ post.title }}</h1>
<p>{{ post.text|linebreaks }}</p>
</div>
{% endblock %}
My urls.py is
from django.conf.urls import include, url
from . import views
urlpatterns = [
url(r'^$', views.post_list, name='post_list'),
url(r'^post/(?P<pk>[0-9]+)/$', views.post_detail, name='post_detail'),
]
and views.py is
from django.shortcuts import render
from django.utils import timezone
from django.shortcuts import render, get_object_or_404
from .models import Post
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
return render(request, 'blog/post_detail.html', {'post': post})
#Post.objects.get(pk=pk)
# Create your views here.
def post_list(request):
return render(request, 'blog/post_list.html', {})
Thanks.
Assuming the first template you've posted is post_list.html you don't send any context variables to it.
In post_list view - if you want to list all posts - you have to add:
def post_list(request):
posts = Post.objects.all()
return render(request, 'blog/post_list.html', {'posts': posts})
Then in your post_list.html template you have to loop over posts:
{% extends 'blog/base.html' %}
{% block content %}
{% for post in posts %} # iterate over posts
<div class="post">
{% if post.published_date %}
<div class="date">
{{ post.published_date }}
</div>
{% endif %}
<h1>{{ post.title }}</h1>
<p>{{ post.text|linebreaks }}</p>
</div>
{% endfor %}
{% endblock %}
There error message complains that it can't find a reverse URL when pk is '', the empty string.
Indeed there is no URL that matches that, as the regular expression required [0-9]+, and the empty string doesn't match that. So a reverse match can't be found.
The reason why pk was empty is explained in the other answer.

DeleteView doesn't delete and just refreshes the delete page

When I click on my delete project link it takes me to my delete page with a button to click which should delete the model data of the project and then take me to the profile page. However when I click the delete button, the page just refreshes and no data gets deleted?!
What am I doing wrong here? Any help would be much appreciated :-)
Views
class DeleteProject(UpdateView):
model = UserProject
template_name = 'howdidu/delete_project.html'
def get_object(self, queryset=None):
obj = super(DeleteProject, self).get_object()
if not obj.user == self.request.user:
raise Http404
return obj
def get_success_url(self):
project_username = self.request.user.username
#project_slug = self.object.slug
return reverse('user_profile', kwargs={'username':project_username})
delete_project.html template
{% extends 'howdidu/base.html' %}
{% load staticfiles %}
{% block title %}Delete project{% endblock %}
{% block body_block %}
<h1>Delete project</h1>
<form method="post">{% csrf_token %}
<p>Are you sure you want to delete "{{ userproject.title }}"?</p>
<input type="submit" value="Confirm" />
</form>
{% endblock %}
Urls
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^register_profile/$', views.register_profile, name='register_profile'),
url(r'^update_profile/$', views.update_profile, name='update_profile'),
url(r'^create_project/$', login_required(views.CreateProject.as_view()), name='create_project'),
url(r'^(?P<username>\w+)/(?P<slug>[-\w]+)/update_project/$', login_required(views.UpdateProject.as_view()), name='update_project'),
url(r'^(?P<username>\w+)/(?P<slug>[-\w]+)/delete_project/$', login_required(views.DeleteProject.as_view()), name='delete_project'),
url(r'^(?P<username>\w+)/$', views.profile_page, name='user_profile'),
url(r'^(?P<username>\w+)/(?P<slug>[-\w]+)/$', views.project_page, name='user_project'),
)
Project.html template which has the delete link on
{% extends 'howdidu/base.html' %}
{% load staticfiles %}
{% block title %}Project{% endblock %}
{% block body_block %}
{% if project %}
<h1>{{ project.title }}</h1>
<img src="{{ project.project_picture.url }}" width = "300" height = "300" />
<h3>{{ project.project_overview }}</h3>
{% if user.is_authenticated %}
{% if project_user.username == user.username %}
<p>Edit project</p>
<p>Delete project</p>
{% endif %}
{% endif %}
{% else %}
The specified project {{ project.title }} does not exist!
{% endif %}
{% endblock %}
You must use DeleteView not UpdateView.
See here.

ListView Django -next prev links in pagination is missing

I working on pagination with ListView with django.
Everything is working as expected. But there is no next and previous links on template.
Am i missing something here ?
Here is urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.views.generic.list import ListView
from demoapp.models import Candidate
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^test/', ListView.as_view(
model=Candidate,
paginate_by='10',
queryset=Candidate.objects.all(),
context_object_name="tasks",
template_name='index.html')),
)
models.py
from django.db import models
class Candidate(models.Model):
name=models.CharField(max_length=255)
And here is index.html
<ol>
{% for t in tasks %}
<li><p>{{t.name}}</p></li>
{% endfor %}
</ol>
<div class="pagination">
<ul>
{% if paginator.has_previous %}
<li>Previous</li>
{% endif %}
{% for pg in paginator.page_range %}
{% if posts.number == pg %}
<li class="active">{{ pg }}</li>
{% else %}
<li>{{ pg }}</li>
{% endif %}
{% endfor %}
{% if paginator.has_next %}
<li>Next</li>
{% endif %}
</ul>
</div>
Nothing shows up because Django doesn't know what paginator is, in the view template.
Looking at the example in the documentation, it seems you need to replace paginator in the view with tasks -
<div class="pagination">
<ul>
{% if tasks.has_previous %}
<li>Previous</li>
{% endif %}
{% for pg in tasks.page_range %}
{% if posts.number == pg %}
<li class="active">{{ pg }}</li>
{% else %}
<li>{{ pg }}</li>
{% endif %}
{% endfor %}
{% if tasks.has_next %}
<li>Next</li>
{% endif %}
</ul>
</div>

Python Django from does not work after refactoring

I have been working through the Tango With Django tutorial. However, I noticed that some of the examples did not adhere to what people consider Django best practices, so I went back to do a little refactoring. Here is how I first wrote a template for a form that allows a user to add a web page to a category.
<!DOCTYPE html>
<html>
{% extends 'rango/base.html' %}
{% block title %}Add a Page{% endblock %}
{% block body_block %}
<h1>Add a Page</h1>
<form id="page_form" method="post" action="/rango/category/{{ category_name }}/add_page/">
{% csrf_token %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% for field in form.visible_fields %}
{{ field.errors }}
{{ field.help_text }}
{{ field }}
{% endfor %}
<input type="submit" name="submit" value="Create Page"></input>
</form>
{%endblock%}
</html>
I then refactored the template like so:
<!DOCTYPE html>
<html>
{% extends 'rango/base.html' %}
{% block title %}Add a Page{% endblock %}
{% block body_block %}
<h1>Add a Page</h1>
<form id="page_form" method="post" action="{% url 'add_page' category_name %}"></form>
{% csrf_token %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% for field in form.visible_fields %}
{{ field.errors }}
{{ field.help_text }}
{{ field }}
{% endfor %}
<input type="submit" name="submit" value="Create Page"></input>
</form>
{%endblock%}
</html>
However, now when I click the submit button, nothing happens. Here is the url pattern that I use:
url(r'^category/(?P<category_name_url>\w+)/add_page/$', views.add_page, name='add_page')
Here is my view:
#login_required
def add_page(request, category_name_url):
category_name = remove_underscores(category_name_url)
if request.method == 'POST':
form = PageForm(request.POST)
if form.is_valid():
page = form.save(commit=False)
try:
cat = Category.objects.get(name=category_name)
page.category = cat
except Category.DoesNotExist:
return render(request, 'rango/add_page.html', {})
page.views = 0
page.save()
return category(request, category_name_url)
else:
print form.errors
else:
form = PageForm()
return render(request, 'rango/add_page.html',
{'category_name_url': category_name_url,
'category_name': category_name,
'form': form})
UPDATE:
Here is the code in urls.py:
from django.conf.urls import patterns, url
from rango import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^about$', views.about, name='about'),
url(r'^add_category/$', views.add_category, name='add_category'),
url(r'^category/(?P<category_name_url>\w+)/$', views.category, name='category'),
url(r'^category/(?P<category_name_url>\w+)/add_page/$', views.add_page, name='add_page'),
url(r'^register/$', views.register, name='register'),
url(r'^login/$', views.user_login, name='login'),
url(r'^restricted/$', views.restricted, name='restricted'),
url(r'^logout/$', views.user_logout, name='logout'),
)
UPDATE:
I print out the result of {% url 'add_page' category_name %} and got /rango/category/Ruby/add_page/, which is the correct result. Looks like the url tag is resolving to the correct path. Still not sure why it is not working.
OMG! I feel so lame! This line was the issue:
<form id="page_form" method="post" action="{% url 'add_page' category_name %}"></form>
The fields and submit button were not enclosed in the form! Ugh!

Categories