I have a ListView and from this I want to delete some objects using DeleteView. What I have so far:
views.py
class BlockListView(ListView):
model= Classroom
def get_context_data(self, **kwargs):
context = super(BlockListView, self).get_context_data(**kwargs)
classroom_blocks = Classroom.objects.all()
context = {'classroom_blocks': classroom_blocks}
return context
list_classroom_view = BlockListView.as_view()
class BlockDeleteView(DeleteView):
model = Classroom
success_url = reverse_lazy('classroom:blocklist')
delete_classroom_view = BlockDeleteView.as_view()
urls.py
urlpatterns = [
path(r'^$', views.index, name='index'),
path('submitted', views.submitted, name='submitted'),
path('classup/', create_classroom_view, name='classroom'),
path('block/', views.block, name='block'),
path('blocklist/', list_classroom_view, name='blocklist'),
path(r'^(?P<pk>\d+)/blockDelete/$', delete_classroom_view, name='blockDelete'),
]
template for listview:
{% for block in classroom_blocks %}
<li>{{ block.get_course_block_display }}DELETE</li>
{% empty %}
<li>No classes set up yet.</li>
{% endfor %}
template for confirm delete:
{% block body %}
<h1>Confirm Delete</h1>
<form action="." method="post">{% csrf_token %}
<p>Are you sure you want to delete "{{ object.course_block }}"?</p>
<input type="submit" value="Confirm" />
</form>
{% endblock %}
After I click the delete button from the listview, the url generated is http://127.0.0.1:8000/classroom/%5E(%3FP89%5Cd+)/blockDelete/$ and this directs to the confirm delete page. After confirming delete, I get a 404 error with Request URL: http://127.0.0.1:8000/classroom/%5E(%3FP89%5Cd+)/blockDelete/
You are using path(), so you shouldn't be using regexes. Change the first and last URL patterns to:
path('', views.index, name='index'),
...
path('<int:pk>/blockDelete/', delete_classroom_view, name='blockDelete'),
Now, when you click on the delete button from the list view, you should be taken to a url like /classroom/1/blockDelete/, and you shouldn't get a 404 when you submit the form.
Related
I'm trying to pass an object's id through the url, but its not able to find the page even after it tries the path when it goes through its patterns
Error:
Using the URLconf defined in GroomingService.urls, Django tried these URL patterns, in this order:
admin/
[name='Home']
appointment-Maker/
account/
admin-home
view_appointment/<id>/
login/ [name='Login Page']
registration/ [name='Registration Page']
logout [name='Logout Page']
The current path, adminview_appointment/21/, didn’t match any of these.
GroomingService.urls
#urls
urlpatterns = [
path('admin/', admin.site.urls),
path('', Home_view, name="Home"),
path('appointment-Maker/', include('appointmentApp.urls')),
path('account/', include('accountApp.urls')),
path('admin-home', include('adminApp.urls')),
path('view_appointment/<id>/', viewAppointment_view), #this is the page it is not finding
path('login/', Login_view, name='Login Page'),
path('registration/', Registration_view, name='Registration Page'),
path('logout', Logout_view, name='Logout Page')
]
adminApp/views.py viewAppointment_view
def viewAppointment_view(request, id):
appointments = Appointment.objects.get(id = id)
context = {
'appointments' : appointments
}
return render(request, "admin_templates/viewappointment.html", context)
templates/admin_templates viewappointment.html
{% extends 'base.html' %}
{% block content %}
<a>appointment view</a>
{% endblock %}
templates/admin_templates adminhome.html (the link is clicked through this page)
{% extends 'base.html' %}
{% block content %}
<a>this is the admin page</a>
<br>
{% for a in appointments %}
Client name:{{a.client_dog_name}}<br> {% comment %} this is the link that is clicked {% endcomment %}
{% endfor %}
<br>
<a>find month</a>
<form method="POST">
{% csrf_token %}
{{ monthyear }}
<button class="btn btn-primary" type="submit">click</buttom>
</form>
{% endblock %}
If I'm missing anything please let me know, I had the path at the adminApp/urls.py earlier
urlpatterns = [
path('', views.adminhome_view, name="Admin Home"),
]
but moved it to where it was trying to find the urls. I have no idea why this might not be working.
It should be view_appointment/{{a.id}}, not adminview_appointment/{{a.id}}, but it is better to make use of the {% url … %} template tag [Django-doc]. You can give the view a name:
path('view_appointment/<int:id>/', viewAppointment_view, name='view_appointment'),
and then refer to it in the template:
Client name:{{a.client_dog_name}}<br>
I'm trying to write the controller to search for articles. But the search does not find anything and a template appears that is not specified in the views.py.
# views.py
class SearchView(ListView):
template_name = 'search_view.html'
def get_queryset(self):
query = self.request.GET.get('q')
object_list = Article.objects.filter(Q(title__icontains=query))
return object_list
# urls.py
urlpatterns = [
path('', ArticlesList.as_view(), name='list_view'),
path('<tag>/', ArticlesByTagsList.as_view(), name='articles_by_tags'),
path('articles/<slug:slug>', ArticleDetail.as_view(), name='detail_view'),
path('articles/create/', ArticleCreate.as_view(), name='create_view'),
path('articles/<slug:slug>/', ArticleUpdate.as_view(), name='update_view'),
path('articles/<slug:slug>/delete/', ArticleDelete.as_view(), name='delete_view'),
path('search/', SearchView.as_view(), name='search_view'),
]
#search_view.html
{% extends 'layout/basic.html' %}
{% block content %}
{{ object_list }}
{% endblock %}
The form looks like this
<form action="{% url 'articles:search_view' %}" method="get">
<input type="text" name="q" placeholder="Search...">
</form>
What am I doing wrong?
You should enumerate over the objects, so:
{% extends 'layout/basic.html' %}
{% block content %}
{% for object in object_list %}
{{ object.title }}
{% endfor %}
{% endblock %}
You should also specify the search/ path before the <tag>/ path, since Django always takes the item that first matches, and if you write search/ then it would first match with the <tag>/ and thus not fire the SearchView.
The urlpatterns thus should look like:
urlpatterns = [
# ↓ first specify the search/ path
path('search/', SearchView.as_view(), name='search_view'),
path('<tag>/', ArticlesByTagsList.as_view(), name='articles_by_tags'),
]
an effect of this, is that you can not use search as a tag. If you should be able to visit the articles_by_tags with search as tag, you should define non-overlapping patterns, so:
urlpatterns = [
path('search/', SearchView.as_view(), name='search_view'),
path('tag/<tag>/', ArticlesByTagsList.as_view(), name='articles_by_tags'),
]
I am trying to display filtered objects in my django template however for some reason I don't know django does not display them.
I have a similar views function and template which does indeed display but this particular function does not.
Here are my urls.py, html template and views.py files:
The views.py function responsible for the url:
def game_category_list(request, slug):
template = 'game_category_list.html'
category = get_object_or_404(gameIdentifier, game_choice=slug)
post = gameIdentifier.objects.filter(game_choice=category)
context = {
'category':category,
'post':post,
}
return render(request, template, context)
Url.py (which contains another url called and this does display all the posts associated with the slug.
urlpatterns = [
path('', views.index, name='index'),
path('categories/<slug:slug>', views.game_category_list, name='game_category_list'),
path('<slug:slug>/', views.category_detail, name='game_category'),
]
Here is the html file for the game_category_list function:
{% extends 'base_layout.html' %}
{% block content %}
<div class='gamecategories'>
{% for game in post %}
<div class='gamecategoriesdisplay'>
<h1>{{game.game_name}}</h1>
</div>
{% endfor %}
</div>
{% endblock %}
I don't know why this doesn't work. Any help would be appreciated.
I had a similar problem. it was due to filter not matching capital letters from my categories, you have to make sure your categories are added in lowecase so it match with the slugs in the url. Once you have changed it, you have to reassign the category or it will keep showing the older one
I was doing the Python Crash Course Ex. 19-1: Blogs, and I'm now stuck at saving the edit of any blog. I tried plugging in the .errors code in the blog.html (for showing each blog) but it shows nothing, so I guess my templates has no field errors (?)
Here're some codes I believe crucial for solving the not-saving-the-edit problem. The new_blog function in views.py works fine so I'll skip it.
The edit_blog function in views.py:
def edit_blog(request, blog_id):
idk = BlogPost.objects.get(id = blog_id)
if request.method != "POST":
form = BlogForm(instance = idk)
else:
form = BlogForm(instance = idk, data = request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('blogs:blogs'))
content = {"editing_blog": form, "psst": idk}
return render(request, 'blogs/edit_blog.html', content)
new_blog.html:
{% extends "blogs/all.html" %}
{% block content %}
<p>Write a new blog:</p>
<form action="{% url 'blogs:new_blog' %}" method='post'>
{% csrf_token %}
<table border="1">
{{ new_blog }}
</table>
<p></p>
<button name="submit">Submit</button>
</form>
{% endblock content %}
edit_blog.html:
{% extends "blogs/all.html" %}
{% block content %}
<p>Edit the blog:</p>
<form action="{% url 'blogs:blog' psst.id %}" method='post'>
{% csrf_token %}
<table border="1">
{{ editing_blog }}
</table>
<p></p>
<button name="submit">Save changes</button>
</form>
{% endblock content %}
Btw, the urlpattern is here:
from django.urls import path, include
from . import views
app_name = 'blogs'
urlpatterns = [
# Home page
path('', views.homepage, name = 'homepage'),
# Show all blogs.
path('blogs/', views.blogs, name = 'blogs'),
# Show the detail of a blog.
path('blogs/<int:blog_id>', views.blog, name = 'blog'),
# Page for adding a new blog.
path('new_blog/', views.new_blog, name = 'new_blog'),
# Page for editing a blog.
path('edit_blog/<int:blog_id>', views.edit_blog, name = 'edit_blog'),
]
No matter how I change the title, or content, or both of the blog I don't see the changes saved. Is it:
A) My form action in edit_blog.html goes wrong, as wakandan mentioned?
B) I need to adjust something in edit_blog view function, like Bibhas said?
Many thanks. Also tell me if I need to add more codes for understanding.
Your form action is currently set to {% url 'blogs:blog' psst.id %}, which means you're posting to your views.blog view, which is just a detail view. You need to change the action to {% url 'blogs:edit_blog' psst.id %} so that the form is posted to your edit view.
It's not clear from the code you have posted where the editing_blog context variable is coming from - you will need to make sure that this is an instance of the same form that your edit view is looking for, otherwise you'll run into other problems.
Finally also note that you are not currently handling the case where the form has errors - i.e., there is no else condition specified for form.is_valid().
I'm a django newbie and wanted to integrate Singly into the django Polls application. I have used class based views to allow for models from the singly app to be passed along with the Polls models.
The problem is, I'm unable to get data from the Singly model even when data is present inside the database.
For now I simply want to display the access_token and profile ID of the user profile.
Here is my Views.py code: (only the view in question)
class IndexView(ListView):
context_object_name='latest_poll_list'
queryset=Poll.objects.filter(pub_date__lte=timezone.now) \
.order_by('-pub_date')[:5]
template_name='polls/index.html'
def get_context_data(self, **kwargs):
context = super(IndexView, self).get_context_data(**kwargs)
context['user_profile'] = UserProfile.objects.all()
return context
This is my urls.py:
urlpatterns = patterns('',
url(r'^$',
IndexView.as_view(),
name='index'),
url(r'^(?P<pk>\d+)/$',
DetailView.as_view(
queryset=Poll.objects.filter(pub_date__lte=timezone.now),
model=Poll,
template_name='polls/details.html'),
name='detail'),
url(r'^(?P<pk>\d+)/results/$',
DetailView.as_view(
queryset=Poll.objects.filter(pub_date__lte=timezone.now),
model=Poll,
template_name='polls/results.html'),
name='results'),
url(r'^(?P<poll_id>\d+)/vote/$', 'polls.views.vote', name='vote'),
)
And here is my index.html:
{% load staticfiles %}
<h1>Polls Application</h1>
<h2>Profile Info:</h2>
<div id="access-token-wrapper">
<p>Here's your access token for making API calls directly: <input type="text" id="access-token" value="{{ user_profile.access_token }}" /></p>
<p>Profiles: <input type="text" id="access-token" value="{{ user_profile.profiles }}" /></p>
</div>
<link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}" />
{% if latest_poll_list %}
<ul>
{% for poll in latest_poll_list %}
<li>{{ poll.question }}</li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
Its able to fetch Polls correctly but it doesn't print anything in either textboxes i.e. the user_profile.access_token and the user_profile.profiles.
I think the problem is incorrect rendering of the template. It should pass the context 'user_profile' but its not. Or for some reason its not taking the data from the database, because there is an entry in the UserProfile database.
I would be grateful for your help, people.
The user_profile context variable contains list of UserProfile objects. From code:
context['user_profile'] = UserProfile.objects.all() # will return a QuerySet, that behaves as list
And in template it is accessed as if it is a single object:
{{ user_profile.access_token }}
{{ user_profile.profiles }}
So either put to this variable a single UserProfile object in a view. For example:
if self.request.user.is_authenticated()
context['user_profile'] = UserProfile.objects.get(user=self.request.user)
else:
# Do something for unregistered user
Either iterate over profiles in template:
{% for up in user_profile %}
{{ up.access_token }}
{% endfor %}
Either access to profile by index in template:
{{ user_profile.0.access_token }}