Django - Page not found (404) urls.py - django

problem:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/home/category/coding/
Raised by: blogapp.views.BlogDetailView
urls.py
from django.urls.conf import path
from blogapp.views import BlogDetailView, BlogListView,searchposts,CatListView
from . import views
app_name = "blogapp"
urlpatterns = [
path('', views.BlogListView, name="blogs"),
path('home/search/', views.searchposts, name= "searchposts"),
path('home/category/<slug:_id>/', views.BlogDetailView, name="blog"),
path('home/category/<category>/', views.CatListView.as_view(), name="category"),
]
if i reverse this two
path('home/category/<slug:_id>/', views.BlogDetailView, name="blog"),
path('home/category/<category>/', views.CatListView.as_view(), name="category"),
it shows the html of the category , and the path of 'path('home/category/slug:_id/', views.BlogDetailView, name="blog"),' is not showing , vice versa
here is the html of navbar
{% for category in category_list %}
{% if forloop.counter < 4 %}
<li class="nav-item">
<a class="nav-link" href="home/category/{{category.name}}">{{ category.name|title }}</a>
</li>
{% endif %}
{% endfor %}
html that i want to render
{% extends "_layouts/base.html" %}
{% block css %}
{{block.super}}
{% endblock css %}
{% block page_title %}Insert_your_name_here{% endblock %}
{% load static %} <!-- load the image -->
{% block maincontent %}
<!-- Banner -->
{% block banner %}
{% load static %}
{% include "layout/category_banner.html" %}
{% endblock %}
<!-- Banner Here -->
!-- This is the main template -->
<section class="blog-posts grid-system">
<div class="container">
<div class="row">
<div class="col-lg-8">
<div class="all-blog-posts">
<div class="row">
{% block categories-main %}
{% include "layout/category.html" %}
{% endblock %}
</div>
</div>
</div>
{% block sidebars %}
{% load static %}
{% include "layout/Sidebars.html" %}
{% endblock %}
</div>
</div>
</section>
{% endblock %}
here is my views.py
def BlogDetailView(request,_id):
try:
category_list = Category.objects.exclude(name='default')
dataset = BlogModel.newmanager.all()
data = BlogModel.newmanager.get(slug =_id)
comments = CommentModel.objects.filter(blog = data, status=True)
except BlogModel.DoesNotExist:
raise Http404('Data does not exist')
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
Comment = CommentModel(your_name= form.cleaned_data['your_name'],
comment = form.cleaned_data['comment'],
blog=data)
Comment.save()
return redirect(f'/home/category/{_id}')
else:
form = CommentForm()
context = {
'data':data,
'form':form,
'comments':comments,
'dataset': dataset,
"category_list": category_list,
}
return render(request,'layout/post-details-main.html',context)
def searchposts(request):
dataset = BlogModel.newmanager.all()
if request.method == 'GET':
query= request.GET.get('q')
submitbutton= request.GET.get('submit')
if query is not None:
lookups= Q(blog_title__icontains=query) | Q(blog__icontains=query)
results= BlogModel.objects.filter(lookups).distinct()
context={'results': results,
'submitbutton': submitbutton,
'dataset': dataset,
}
return render(request, 'layout/search-main.html', context)
else:
return render(request, 'layout/search-main.html')
else:
return render(request, 'layout/search-main.html')
class CatListView(ListView):
template_name = 'layout/category-main.html'
context_object_name = 'catlist'
def get_queryset(self):
content = {
'cat' : self.kwargs['category'],
'posts' :
BlogModel.objects.filter(category__name=self.kwargs['category']).filter(status='published')
}
return content
def category_list(request):
category_list = Category.objects.exclude(name='default')
context = {
"category_list": category_list,
}
return context
it says that the problem is raised by blogapp.views.BlogDetailView so i added this to my BlogDetailView render it to my main html :
category_list = Category.objects.exclude(name='default')
context = {
"category_list": category_list,
}
i think the problem is the link? of my navbar or the BlogDetailView?, What is the problem of this?

You have to accept it as string
Try like this:
path('home/category/<str:category>/', views.CatListView.as_view(), name="category"),

Case is solved i using both str and slug, so my category does not match to my _id, need to match those two
path('home/category/<slug:category>/', views.CatListView.as_view(), name="category"),
path('home/category/<slug:_id>/', views.BlogDetailView, name="blog")

Related

Add link on a web page to export tables2 data in Django

I'm trying to include a link on a webpage to download a tables2 table to csv. I got the commented out piece below from the documentation, and I think it might just need a simple tweak to get it to work with my code. Any thoughts?
views.py
class PlatListView(SingleTableMixin, FilterView):
model = Plat
template_name = 'blog/filtertable.html'
filter_class = PlatFilter
def get_context_data(self, **kwargs):
context = super(PlatListView, self).get_context_data(**kwargs)
query = Phase.objects.all().select_related('plat','plat__community')
f = PlatFilter(self.request.GET, queryset=query)
t = PlatTable(data = f.qs)
RequestConfig(self.request, paginate=False).configure(t)
context['filter'] = f
context['table'] = t
'''
export_format = self.request.GET.get("_export", None)
if TableExport.is_valid_format(export_format):
exporter = TableExport(export_format, query)
return exporter.response("query.{}".format(export_format))
'''
return context
filtertable.html
{% extends "blog/base.html" %}
{% block content %}
{% load querystring from django_tables2 %}
<div style = 'padding-top: 24px'>
Download CSV
</div>
{% load render_table from django_tables2 %}
{% load bootstrap4 %}
{% if filter %}
<form action="" method="get" class="form form-inline">
{% bootstrap_form filter.form layout='inline' %}
{% bootstrap_button 'filter' %}
</form>
{% endif %}
{% render_table table 'django_tables2/bootstrap4.html' %}
{% endblock content %}
The commented-out snippet in your code is for function-based views as mentioned in the docs. In your case you should just add the ExportMixin :
from django_tables2.export.views import ExportMixin
class PlatListView(SingleTableMixin, ExportMixin, FilterView):
# other stuff your view is doing

My view is taking me to the same page over and over

Hey guys I made a model that can upload some files and then i made two views upload_list.html and upload_detail.html the list pages contains the links to the actual detail page but while clicking on the links it takes me to the same page again
Here,s the models.py
class Upload(models.Model):
image = models.ImageField(upload_to = 'images',)
file = models.FileField(upload_to = 'images/%Y/%M/%d/')
name = models.CharField(max_length = 200)
def __str__(self):
return self.name
def get_absolute_url(self):
return self.pk{}
Here,s the views.py
def upload_list(request):
upload_list = Upload.objects.all()
return render(request,'app/upload_list.html',{'upload_list':upload_list})
def upload_detail(request,pk):
upload_detail = get_object_or_404(Upload,pk = pk)
return render(request,'app/upload_detail.html',{'upload_detail':upload_detail})
Hers, the urls.py
url(r'^upload/',views.upload_list,name = 'upload_list'),
url(r'^upload/(?P<pk>[-\w]+)/$',views.upload_detail,name = 'upload_detail'),
Hers, the upload_list.html
{% extends 'app/base.html' %}
{% block content %}
{% load static %}
{% for i in upload_list %}
<div class="jumbotron">
{{i.name}}
<br>
</div>
{% endfor %}
{% include 'app/index_js.html' %}
{% endblock content %}
Here,s the upload_Detail.html
{% extends 'app/base.html' %}
{% block content %}
{% load static %}
<div class="jumbotron">
<h1>{{upload_detail.name}}</h1>
<img src="{{upload_detail.name}}" alt="'Image for you,r betterment "></img>
{{upload_detail.file}}
</div>
{% include 'app/index_js.html' %}
{% endblock conten`t %}`
Have you tried put your urls.py like this ?
url(r'^upload/$',views.upload_list,name = 'upload_list'),
url(r'^upload/(?P<pk>[-\w]+)/$',views.upload_detail,name = 'upload_detail'),
or
url(r'^upload/(?P<pk>[-\w]+)/$',views.upload_detail,name = 'upload_detail'),
url(r'^upload/$',views.upload_list,name = 'upload_list'),
The $ is a regex that indicates a end of string.
I hope that helps you

How to Create a UpdateForm with TemplateView?

I need to create a UpdateForm with a TemplateView. Why with TemplateView? Because, I has a attribute what is geo_location, and I'm using LeafLet maps, and LeafLet maps doesn't work with generic.UpdateView or others the same type.
Here my views from Update:
class UpdateStore(LoginRequiredMixin, TemplateView):
template_name = 'store_form'
success_url = reverse_lazy('register:store_list')
def post(self, request, *args, **kwargs):
store_id = kwargs['store']
store = get_object_or_404(Store, pk=store_id)
form = StoreForm(request.POST, on_edit=True)
if form.is_valid():
form.save()
return redirect(reverse('register:store_list'))
else:
context = self.get_context_data()
context['data_form'] = form
return render(request, self.template_name, context)
return self.get(request)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
store_id = self.kwargs['store']
store = get_object_or_404(Store, pk=store_id)
data = {
'name': store.name,
'description': store.description,
'address': store.address,
'geo_loc': store.geo_loc,
'opened': store.opened
}
context['editing'] = True
context['data_form'] = StoreForm(initial=data, on_edit=True)
context['store'] = store
return context
Here is my template code:
{% extends 'base.html' %}
{% load bootstrap3 %}
{% load leaflet_tags %}
{% block extra_css %}
{% leaflet_css plugins="forms" %}
{% endblock %}
{% block body %}
<h1> Update Store </h1>
<form method="POST">
{% csrf_token %}
{{ form }}
{% buttons %}
<button type="submit">
{% bootstrap_icon "star" %} Save
</button>
{% endbuttons %}
</form>
{% endblock %}
{% block extra_js %}
{% leaflet_js plugins="forms" %}
{% endblock %}
I trying this, but in my template, the Forms doesn't load, and my template are blanked :(. Someone knows why? I need another method for get anything else?
Thanks.
The problem with your code is that you place the form in the data_form key of the context:
context['data_form'] = StoreForm(initial=data, on_edit=True)
and then on the template you try to use it with {{form}} instead of {{data_form}}. After that the form should be rendered.

Reverse for 'user_review_list' not found. 'user_review_list' is not a valid view function or pattern name

Even after going through similar STACKOVERFLOW solutions this doubt was not solved.
I have also been through other resources.
Been engaged in django since 2 days only !! :)
project -> winerama
app ->reviews
my views.py
def review_list(request):
latest_review_list =Review.objects.order_by('-pub_date')[:9]
context ={'latest_review_list': latest_review_list}
return render(request, 'reviews/review_list.html',context)
def wine_list(request):
wine_list =Wine.objects.order_by('-name')
context ={'wine_list':wine_list}
return render(request, 'reviews/wine_list.html',context)
def review_detail(request , review_id):
review = get_object_or_404(Review , pk = review_id)
context = {'review':review}
return render(request,'reviews/review_detail.html',context)
def wine_detail(request , review_id):
wine = get_object_or_404(Wine, pk = wine_id)
context = {'wine':wine}
return render(request,'reviews/wine_detail.html',context)
def add_review(request,wine_id):
wine = get_object_or_404(Wine , pk = wine_id)
form = ReviewForm(request.POST)
if form.is_valid():
rating = form.cleaned_data['rating']
comment = form.cleaned_data['comment']
user_name=form.cleaned_data['user_name']
review =Review()
review.wine = wine
review.user_name = user_name
review.user_name = user_name
review.rating =rating
review.comment = comment
review.pub_date = datetime.datetime.now()
review.save()
return HttpRespponseRedirect(reverse('reviews:wine_detail',args = (wine.id,)))
return render(request,'reviews/wine_detail.html',{'wine':wine,'form':form})`
reviews/urls.py
urlpatterns = [
# ex: /
url(r'^$', views.review_list, name='review_list'),
# ex: /review/5/
url(r'^review/(?P<review_id>[0-9]+)/$', views.review_detail, name='review_detail'),
# ex: /wine/
url(r'^wine$', views.wine_list, name='wine_list'),
# ex: /wine/5/
url(r'^wine/(?P<wine_id>[0-9]+)/$', views.wine_detail, name='wine_detail'),
url(r'^wine/(?P<wine_id>[0-9]+)/add_review/$', views.add_review, name='add_review'),
]
reviews/templates/reviews/base.html
{% block bootstrap3_content %}
<div class="container">
<nav class="navbar navbar-default">
<div class="navbar-header">
<a class="navbar-brand" href="{% url 'review_list' %}">Winerama</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>Wine list</li>
<li>Home</li>
</ul>
</div>
</nav>
<h1>{% block title %}(no title){% endblock %}</h1>
{% bootstrap_messages %}
{% block content %}(no content){% endblock %}
</div>
{% endblock %}
THANKS IN ADVANCE.
PLEASE HELP ME FOR THE SAME.
The error is self explanatory:
Somewhere in your template html you have written
{% url 'user_review_list' %}
That means you are calling user_review_list function, but it is not defined in views. Instead you have defined review_list function.

Django uploaded files not displaying in template page

I am trying to display the top 5 recently posted files but doesnt seem to show up.
When i get all the objects by using Model.objects.all(), it gives me all the objects from Db but when i am trying to get the top 5, it does not display.
Kindly help and suggest me. Thanks
my views.py is
def about_experiment(request, ex_link_name):
researcher = None
study = None
posts = None
exp = get_object_or_404(Experiment,link_name = ex_link_name)
high_scores = ScoreItem.objects.filter(experiment=exp,active=True)
context = {
'request': request,
'exp':exp,
'high_scores': high_scores,
'awards':AwardItem.objects.filter(experiment=exp,visible=True),
'posts':Help.objects.filter().order_by('-date')[0],
'documents':Help.objects.filter().order_by('-document')[:5]
}
if exp.about_file:
context['about_file'] = settings.EXPERIMENT_DIRS+exp.about_file.get_include_path()
if request.method == 'POST':
form = AboutHelp(request.POST, request.FILES)
if form.is_valid():
obj = form.save(commit = False)
obj.save()
return HttpResponseRedirect('/about/%s/' %ex_link_name)
#return redirect(reverse('lazer.views.about_experiment', kwargs={ 'ex_link_name':obj.link_name }))
else:
form = AboutHelp()
return render(request, 'about_experiment.html', context)
destination template page
<div class="tab-pane" id="irb">
<h4> List of file(s) uploaded:</h4>
<!--File upload-->
{% if documents %}
<ul>
<li> {{ documents.document }} </li>
</ul>
{% else %}
<p>No such documents available.</p>
{% endif %}
<!--File upload ends-->
documents is a queryset and you are picking top 5. You need to do this like this.
<div class="tab-pane" id="irb">
<h4> List of file(s) uploaded:</h4>
<!--File upload-->
{% for doc in documents %}
<ul>
<li> {{ doc.document }} </li>
</ul>
{% empty %}
<p>No such documents available.</p>
{% endfor %}
<!--File upload ends-->