NoReverse Match at Delete View - python

I started coding with Python and Django last week and now I start getting desperate about it.
I have to work on a To-Do-List and want to delete ToDo task by clicking on a button next to the task.
Now I always get a
NoReverseMatch at /delete/1
error :(
The delete_confirm.html:
{% extends "base_page.html" %}
{% block title %}Confirm Todo delete{% endblock %}
{% block content %}
<form action="" method="post">{% csrf_token %}
<p>Are you sure you want to delete "{{ object }}"?</p>
<input type="submit" value="Confirm" />
</form>
{% endblock %}
My Urls.py:
from django.conf.urls import patterns, url
from todolist import views
urlpatterns = patterns('',
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^add', views.AddView.as_view(), name='add'),
url(r'^impressum', views.ImpressumView.as_view(), name='impressum'),
url(r'^edit/(?P<pk>\d+)$', views.UpdateView.as_view(), name='todo_edit'),
url(r'^delete/(?P<pk>\d+)', views.DeleteView.as_view(), name='todo_delete'),
)
The views.py:
from django.shortcuts import render
from django.core.urlresolvers import reverse_lazy
from django.http import HttpResponse
from django.views import generic
from django.views.generic import TemplateView, ListView, CreateView, UpdateView, DeleteView
from todolist.models import Todo
# Create your views here.
class IndexView(ListView):
template_name = 'index.html'
model = Todo
class ImpressumView(TemplateView):
template_name = 'impressum.html'
class AddView(CreateView):
template_name = 'add.html'
model = Todo
fields = ['title','deadline','progress']
success_url = '/'
class UpdateView(UpdateView):
template_name = 'edit.html'
model = Todo
fields = ['title','deadline','progress']
success_url = '/'
class DeleteView(DeleteView):
template_name = 'delete_confirm.html'
model = Todo
success_url = reverse_lazy('/')
The interesting part of the index.html:
<!--Table content-->
{% for todo in object_list %}
<tr>
<td class="text-left">{{todo.title}}</td>
<td> {{todo.deadline}}</td>
<td>
<div class="progress">
<div class="progress-bar" role="progressbar" aria-valuenow="{{todo.progress}}" aria-valuemin="0" aria-valuemax="100" style="width: {{todo.progress}}%">
{{todo.progress}}%
</div>
</div>
</td>
<td >
<div class="btn-group">
Edit
Delete
<button class="btn btn-default" data-toggle="tooltip" title="Done?" data-placement="right"><span class="glyphicon glyphicon-check"></button>
</div>
</td>
{% endfor %}
Would be great if some of your guys could help a newbie :)

The problem is this line in your delete view.
class DeleteView(DeleteView):
...
success_url = reverse_lazy('/')
You can either provide the url:
success_url = '/'
or use reverse_lazy with the url name that you wish to reverse:
success_url = reverse_lazy('index')

Related

Page not found (404) No comment found matching the query

views.py
class CommentCreatView(LoginRequiredMixin, CreateView):
model = Comment
fields = ['text']
template_name = 'home/add-comment.html'
success_url = 'homepage'
def form_valid(self,form):
form.instance.user = self.request.user
post = self.get_object()
form.instance.post = post
return super().form_valid(form)
urls.py
from django.urls import path
from . import views
from django.conf import settings
from django.conf.urls.static import static
from .views import PostCreateView, PostsListView, PostDetailView, CommentCreatView
urlpatterns = [
path('', PostsListView.as_view(), name='homepage'),
path('post/<int:pk>/', PostDetailView.as_view(), name='post-and-comments'),
path('post/<int:pk>/comment', CommentCreatView.as_view(), name='add-comment'),
path('creat', PostCreateView.as_view(), name='creat-post')
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
add-comment.html
{% extends "home/base.html" %}
{% load crispy_forms_tags %}
<!-- allow us to use crispy filter on any of our forms -->
{% block content %}
<div class="content-section">
<form method="POST">
<!--this method post is to protect our form fromcertain attacks -->
{% csrf_token %}
{{form|crispy}}
<button class="btn btn-outline-danger mt-1 mb-1 mr-1 ml-1" type="submit">Add Comment</button>
</div>
</form>
</div>
{% endblock content %}
So I opens it home/post/6/comment , I see the form and when I submit it. I get this error and the comment isnt saved error screenshot
The .get_object(…) [Django-doc] method will try to find a Comment with as primary key the one you specified in the path (here 6). You do not want to find a comment but the Post with that primary key. You thus should rewrite this to:
class CommentCreatView(LoginRequiredMixin, CreateView):
model = Comment
fields = ['text']
template_name = 'home/add-comment.html'
success_url = 'homepage'
def form_valid(self,form):
form.instance.user = self.request.user
form.instance.post_id = self.kwargs['pk']
return super().form_valid(form)

Django ListView is missing a QuerySet - Error Message - 2 Models In 1 View

I'm trying to view data from 2 models in a single list view. I'm getting the below error message and I can't seem to figure out why. I have included the browser error, views.py, urls.py and html page. Any assistance would be appreciated and as a side note I'm new to programming, Python and Django.
Error:
ImproperlyConfigured at /scripts/patientsdetails/
PatientListView is missing a QuerySet. Define PatientListView.model, PatientListView.queryset, or override PatientListView.get_queryset().
Request Method: GET
Request URL: http://127.0.0.1:8000/scripts/patientsdetails/
Django Version: 3.2.2
Exception Type: ImproperlyConfigured
Exception Value:
PatientListView is missing a QuerySet. Define PatientListView.model, PatientListView.queryset, or override PatientListView.get_queryset().
urls.py
from django.urls import path
from .views import (
ScriptListView,
ScriptUpdateView,
ScriptDetailView,
ScriptDeleteView,
ScriptCreateView,
PatientListView,
PatientUpdateView,
PatientDetailView,
PatientDeleteView,
PatientCreateView,
)
urlpatterns = [
path('patientsdetails/',
PatientListView.as_view(), name='patient_list'),
]
views.py
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import ListView, DetailView
from django.views.generic.edit import UpdateView, DeleteView, CreateView
from django.urls import reverse_lazy
from bootstrap_datepicker_plus import DatePickerInput, TimePickerInput
from django.contrib.auth import get_user_model
from django.shortcuts import render
from scripts.models import Patient, Script
from .models import Script, Patient
class PatientListView(LoginRequiredMixin, ListView):
template_name = 'patient_summary.html'
def get_context_data(self, **kwargs):
context = super(PatientListView, self).get_context_data(**kwargs).filter(author=self.request.user)
context['patient'] = Patient.objects.filter(author=self.request.user)
context['script'] = Script.objects.filter(author=self.request.user)
return context
html
{% for patient in object_list %}
<div class="card">
<div class="card-header">
<span class="font-weight-bold">{{ patient.patient_name }}</span> ·
<span class="text-muted"></span>
</div>
<div class="card-body">
Cycle Start Date - {{ patient.cycle_start_day }} <br>
{% endfor %}
{% for script in object_list %}
Drug Name - {{ script.drug_name }} <br>
{% endfor %}
</div>
<div class="card-footer text-center text-muted">
</div>
</div>
<br />
I think it's clear from the error that you have to define which model/queryset attribute to work upon by list view
Do this in your view:
model = Patient
Or
queryset = Patient.objects.all()
Or override get_queryset method
def get_queryset(self):
return Patient.objects.all()

Django DeleteView doesn't delete the object from data

I've just learned CreateView UpdateView and DeleteView models and then I got all of them working. I can change my object I can delete them, but after deleting an object I try to create another and creates one like the before hasn't been deleted. giving me the following pk of the deleted before
it still creates de object although the pk at the moment should be 3, I think after I click the delete button and confirm delete it isn't deleting from data.
These are my models:
from django.db import models from django.urls import reverse
class Dreams (models.Model):
titulo = models.CharField(max_length=100)
objetivo = models.CharField(max_length=100)
imagem = models.CharField(max_length=100)
def get_absolute_url(self):
return reverse ('webdeve:index', kwargs={'pk': self.pk})
def __str__(self):
return self.titulo + ' - ' + self.objetivo
class Which (models.Model):
lets = models.ForeignKey(Dreams, on_delete=models.CASCADE)
make = models.CharField(max_length=100)
it = models.CharField(max_length=100)
favorite = models.BooleanField(default=False)
def __str__(self):
return self.make
my views.py:
from django.views import generic
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from .models import Dreams, Which
from django.urls import reverse_lazy
class IndexView (generic.ListView):
template_name = 'index.html'
def get_queryset(self):
return Dreams.objects.all()
class DetailView (generic.DetailView):
model = Dreams
template_name = 'detail.html'
class DreamCreate (CreateView):
model = Dreams
fields = ['titulo', 'objetivo', 'imagem']
template_name = 'dreams_form.html'
class DreamUpdate (UpdateView):
model = Dreams
fields = ['titulo', 'objetivo', 'imagem']
template_name = 'dreams_form.html'
class DreamDelete (DeleteView):
model = Dreams
template_name= ('dreams_confirm_delete.html')
success_url= reverse_lazy('webdeve:index')
my urls.py:
from django.conf.urls import url
from webdeve import views
app_name = 'webdeve'
# Dreams
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
# Dreams/detail
url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'),
# Dreams/detail/add
url(r'^dream/add/$', views.DreamCreate.as_view(), name='dream-add'),
# Dreams/detail/Update
url(r'^dream/(?P<pk>[0-9]+)/$', views.DreamUpdate.as_view(), name='dreams-uptdate'),
# Dreams/detail/detete
url(r'^dream/(?P<pk>[0-9]+)/delete/$', views.DreamDelete.as_view(), name='dreams-delete'),
]
And my index.html with delete button:
<!-- linkando css no html -->
{% extends 'base.html' %}
{% block nav %}
<ul>
{% for Dreams in object_list %}
<img src={{ Dreams.imagem }}>
<li> {{ Dreams.titulo }} - {{ Dreams.objetivo }} <li>
<!--delete BUTTON-->
<form action="{% url 'webdeve:dreams-delete' Dreams.id %}">
{% csrf_token %}
<input type="hidden" name="dreams_id" value="{{ Dreams.id }}" method="post" style="display: inline" >
<button type="submit" class="btn btn-default btn-sm">
<span class="glyphicon glyphicon-trash"></span>
</button>
</form>
{% endfor %}
</ul>
{% endblock %}
DeleteView only deletes your object on POST, not GET. As a result, you need to use method="post" in your form since GET would render this confirm_delete.html again.
<form method="post" action="">
...
</form>
If you can get into DeleteView on GET, action="" is all you need to POST.

Creating an admin panel for Django site

What I would like to have is an admin panel that I create where only users with permissions set to "admin" in the UserLevel model can edit certain aspects of the website. However, while I think I have everything coded out properly it isn't working. The way I'm trying to implement this already work on the main content section of my site. My best guess is that since I'm trying to cross-use views between apps something got mixed up, although that may be wrong. Also please keep in mind that while I definitely started with clean code which emulated the code from the working parts of the site this code may not so clean because I have been playing around with it so much that I'm just flat out confused... so any help would be much appreciated.
To be clear, there's no error with the site which is why I think the code is written correctly. However, I made a test widget which is not displaying on the home page at all (it's supposed to), nor will it display on the admin panel page I setup (which is supposed to display any widgets there may be), and I can't get the form for adding a new widget to display on the admin panel page either (it gives me a button to go to another page that has the form on it).
Project urls.py:
"""colors URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
from django.conf.urls import include
from accounts import views
from colorsets import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$',views.PostListView.as_view(),name='index'),
url(r'^accounts/',include('accounts.urls',namespace='accounts')),
url(r'^colorsets/',include('colorsets.urls',namespace='colorsets')),
url(r'^adminpanel/',include('adminpanel.urls',namespace='adminpanel')),
]
Adminpanel app urls.py:
from django.conf.urls import url
from adminpanel import views
app_name = 'adminpanel'
urlpatterns = [
url(r'^settings/',views.SettingsListView.as_view(),name='settings'),
url(r'^new/$',views.CreateWidgetView.as_view(),name='create-widget'),
url(r'^delete/$',views.DeleteWidget.as_view(),name='delete-widgets'),
]
Adminpanel app views.py:
from django.shortcuts import render
from adminpanel.forms import WidgetForm
from adminpanel.models import Widget
from django.utils import timezone
from django.contrib.auth import authenticate,login,logout
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse,reverse_lazy
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from braces.views import SelectRelatedMixin
from django.views.generic import (TemplateView,ListView,
DetailView,CreateView,
UpdateView,DeleteView)
# Create your views here.
class CreateWidgetView(LoginRequiredMixin,CreateView):
login_url = '/login/'
redirect_field_name = 'index.html'
form_class = WidgetForm
model = Widget
def form_valid(self,form):
self.object = form.save(commit=False)
self.object.save()
return super().form_valid(form)
class SettingsListView(ListView):
login_url = '/login/'
redirect_field_name = 'index.html'
form_class = WidgetForm
model = Widget
def form_valid(self,form):
self.object = form.save(commit=False)
self.object.save()
return super().form_valid(form)
def get_query(self):
return Widget.object.filter(order_by('widget_order'))
class DeleteWidget(LoginRequiredMixin,SelectRelatedMixin,DeleteView):
model = Widget
select_related = ('Widget',)
success_url = reverse_lazy('settings')
def get_queryset(self):
queryset = super().get_query()
return queryset.filter(user_id=self.request.user.id)
def delete(self):
return super().delete(*args,**kwargs)
Colorsets app views.py (Where I started mixing things):
from django.shortcuts import render
from colorsets.forms import ColorForm
from colorsets import models
from colorsets.models import ColorSet
from adminpanel.models import Widget
from django.utils import timezone
from django.contrib.auth import authenticate,login,logout
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse,reverse_lazy
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from braces.views import SelectRelatedMixin
from django.views.generic import (TemplateView,ListView,
DetailView,CreateView,
UpdateView,DeleteView)
# Create your views here.
#def index(request):
# return render(request,'index.html')
class PostListView(ListView):
model = ColorSet
model = Widget
def get_queryset(self):
return ColorSet.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')
return Widget.objects.filter(order_by('widget_order'))
class CreateColorSetView(LoginRequiredMixin,CreateView):
login_url = '/login/'
redirect_field_name = 'index.html'
form_class = ColorForm
model = ColorSet
def form_valid(self,form):
self.object = form.save(commit=False)
self.object.user = self.request.user
self.object.save()
return super().form_valid(form)
class DeletePost(LoginRequiredMixin,SelectRelatedMixin,DeleteView):
model = models.ColorSet
select_related = ('user',)
success_url = reverse_lazy('index')
def get_queryset(self):
queryset = super().get_queryset()
return queryset.filter(user_id=self.request.user.id)
def delete(self,*args,**kwargs):
return super().delete(*args,**kwargs)
Adminpanel app models.py:
from django.db import models
# Create your models here.
class Widget(models.Model):
name = models.CharField(max_length=50)
widget_order = models.IntegerField(default=0)
body = models.TextField(max_length=500)
def __str__(self):
return self.name
widget_list.html:
{% extends "base.html" %}
{% block content %}
<div class="container">
<div class="content">
{% for widget in widget_list %}
<p>{{ widget.body }}</p>
{% endfor %}
</div>
</div>
{% endblock %}
_post.html:
<div class="post media">
<div class="media-body">
<strong>{{ colorset.user.username }}</strong>
<div class="media-footer">
{% if user.is_authenticated and UserLevels.access_level == 'admin' %}
<a href="{% url 'colorsets:delete' pk=colorset.pk %}" title="delete" class="btn btn-simple">
Delete
</a>
{% endif %}
</div>
</div>
</div>
widget_form.html:
{% block content %}
<div class="colorset-base">
<h2>Create new widget</h2>
<form id="postForm" action="{% url 'adminpanel:create-widget' %}" method="POST">
{% csrf_token %}
{{ form }}
<button type="submit" class="submit btn btn-primary btn-large">Add Widget</button>
</form>
</div>
{% endblock %}
settings.html:
{% extends "base.html" %}
{% block content %}
<div class="container">
<h2>Settings:</h2>
</div>
{% endblock %}
widget_confirm_delete.html:
{% extends 'base.html' %}
{% block content %}
<h3>Are you sure you want to delete this widget?</h3>
<div class="posts">
{% include "adminpanel/_post.html" with post=object hide_delete=True %}
</div>
<form method="POST">
{% csrf_token %}
<input type="submit" value="Confirm Delete" class="btn btn-danger btn-large" />
<a class="btn btn-simple btn-large" href="{% url 'adminpanel/settings'%}">Cancel</a>
</form>
{% endblock %}
I know not everything is being used by things but this is everything I have.

Django objects.all() doesn`t display any content

Hi everybody!
Im just starting a way of django programming so sometimes really get confused.
I`m trying to display all my objects from DB, but when opening the page its simply empty.
There are content added and I tried ListView previously and it worked for me. But now I need to dislpay objects like a grid and here is an issue with this method.
Will be very thanksfull for any help!
models.py
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=140)
body = models.TextField()
date = models.DateField()
image = models.ImageField(upload_to='bons_images/%Y/%m/%d')
def __str__(self):
return self.title
views.py
from django.shortcuts import render, render_to_response
from django.template import RequestContext
from django.views import generic
from blog.models import Post
def image(request):
post = Post()
variables = RequestContext(request, {
'post': post
})
return render_to_response('blog/post.html', variables)
# class IndexView(generic.ListView):
# template_name = 'blog/blog.html'
# context_object_name = 'all_posts'
#
# def get_queryset(self):
# return Post.objects.all()
def index(request):
posts = Post.objects.all()
return render(request, 'blog/blog.html', {'posts': posts})
urls.py
from django.conf.urls import url, include
from django.views.generic import ListView, DetailView
from blog.models import Post
from blog import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^(?P<pk>\d+)$', DetailView.as_view(model=Post, template_name='blog/post.html')),
]
blog.html
{% extends 'base.html' %}
{% block content %}
{% if all_posts %}
{% for post in all_posts %}
<div class="container-fluid">
<div class="row">
<div class="col-sm-3 col-lg-4">
<div class="thumbnail">
<a href="/blog/{{ post.id }}">
<h5>{{ post.date|date:'Y-m-d' }} {{ post.title }}</h5>
<img src="{{ post.image.url }}" style="width: 50%; height: 50%"/>
</a>
</div>
</div>
</div>
</div>
{% endfor %}
{% endif %}
{% endblock %}
And by the way, how its possible to display your objects like in grid, not list, using Bootstrap or so on.
Thank you!
You're iterating over something called all_posts in your template. But your view doesn't send anything called all_posts; it only sends posts. You need to use consistent names.

Categories