page not found error in Django using a filter query {return Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')} - django

I am making my first django practice project I have a view called PostListview :
from django.shortcuts import render
from django.utils import timezone
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.decorators import login_required
from blog.models import Post, Comment
from blog.forms import PostForm,CommentForm
from django.urls import reverse_lazy
from django.views.generic import(TemplateView,ListView,DetailView,CreateView,UpdateView,
DeleteView)
class AboutView(TemplateView):
template_name = 'about.html'
class PostListView(ListView):
model = Post
def get_queryset(self):
return Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')
I have this in in the urls:
from django.conf.urls import url
from blog import views
urlpatterns = [
url(r'^$',views.PostListView.as_view(), name= 'post_list'),
And this is the template which is calling this view.
<li class="navbar-brand bigbrand" >My Tech Blog</li>
This view is also set as the default home view and it opens fine at the time i open the site url (localhost) but when I am clicking "My Tech blog " it gives a 404 error.
This is the main urls.py :
from django.contrib import admin
from django.urls import path
from django.conf.urls import url, include
from django.contrib.auth import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'',include('blog.urls')),
url(r'accounts/login/$',views.login, name = 'login'),
url(r'accounts/logout/$',views.logout, name = 'logout',kwargs={'next_page':'/'}),
]

Just change
url(r'^$',views.PostListView.as_view(), name= 'post_list'),
with
url(r'',views.PostListView.as_view(), name= 'post_list'),

Related

onw of my two app is not working in django

Below is my code. In my hello_world project there is two app pages. one is home page and another is profile page. home page is working fine, but profile page is showing error.
hello_world urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('home_page.urls',)),
path('profile_page',include('profile_page.urls',))
]
home page urls.py
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
path('',views.home,name='home page'),
]
home page views.py
from django.http import HttpResponse
def home(request):
return HttpResponse('home page')
profile page urls.py
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
path('profile_page',views.profile,name='profile page'),
]
profile page views.py
from django.http import HttpResponse
def profile(request):
return HttpResponse('profile page')
You need to use redirect method and include view name space as an argument..
Find the updated code:
from django.http import HttpResponse
def profile(request):
return redirect('profile page')
Don't forgot to import redirect...
The first argument of the path() function, i.e. the 'route' argument, must end with a forward slash.
path('profile_page/',include('profile_page.urls',))
Notice the forward slash at the end of the first argument, 'profile_page/'.
Your URLconf is not matching the expected pattern because of the missing slash.

My url not reading my function in views.py in DJANGO (found similar question not able to trace my issue)

mysite/urls.py
from django.contrib.auth import views
from django.views.generic.base import TemplateView
urlpatterns = [
url('update_db/(<dbname>)/', include('polls.urls')),
url(r'^admin/', admin.site.urls),
url('mysite/login/', auth_views.LoginView.as_view(),name='login'),
url(r'^fetch/',include('polls.urls')),
url('mysite/logout/$', auth_views.logout, name='logout'),
]
polls.urls.py
from django.conf.urls import url
from . import views
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
urlpatterns = [
url('update_db/(?P<dbname>\w+)/$', login_required(views.MyView.get), name='x'),
url('', login_required(views.IndexView.as_view())),
]
fetch.html
<td>click</td>
polls/views.py
from django.shortcuts import render
from django.views.generic import TemplateView , ListView
from django.views.generic.edit import UpdateView
# Create your views here.
from django.http import HttpResponse
from .models import Item , DbRestorationLogDetails
class MyView(UpdateView):
logger.error('Something went wrong!')
print "THANKS FOR UPDATING"
template_name='fetch.html'
model = DbRestorationLogDetails
fields =['verification_status']
def get(self,request, dbname):
usname=request.user
print usname
print dbname
if request.method == "GET":
dblog = DbRestorationLogDetails.objects.get(dbname=dbname)
dblog.verification_status = 'Verified'
print dblog.verification_status
dblog.save()
#.update(dblogdetails.verification_status = 'Verified')
return HttpResponseRedirect(request.GET.get('next'))
NOTE: NOT able to reach to MyView.get() and no db update happening. I assume my code is not able to read my function.

ImportError: cannot import name Upload

I am working on Django, django-rest project and as I have searched the problem, it is beleived I have circular problem, but I don`t think so...
Relevant parts of problem are here:
demo/views.py
from django.shortcuts import render
from rest_auth.models import Upload, UploadForm
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
# Create your views here.
def home(request):
if request.method=="POST":
img = UploadForm(request.POST, request.FILES)
if img.is_valid():
img.save()
return HttpResponseRedirect(reverse('imageupload'))
else:
img=UploadForm()
images=Upload.objects.all()
return render(request,'home.html',{'form':img,'images':images})
rest_auth/models.py
from django.conf import settings
from rest_framework.authtoken.models import Token as DefaultTokenModel
from .utils import import_callable
from django.db import models
from django.forms import ModelForm
class Upload(models.Model):
pic = models.ImageField("Image", upload_to="images/")
upload_date=models.DateTimeField(auto_now_add =True)
# FileUpload form class.
class UploadForm(ModelForm):
class Meta:
model = Upload
and
demo/urls.py
from django.conf.urls import include, url
from django.contrib import admin
from django.views.generic import TemplateView, RedirectView
from django.conf import settings
from django.conf.urls.static import static
from views import home
from rest_framework_swagger.views import get_swagger_view
import os
PROJECT_DIR=os.path.dirname(__file__)
urlpatterns = [
url(r'^$', TemplateView.as_view(template_name="home.html"), name='home'),
url(r'^upload/$', views.home, name='imageupload'),
url(r'^signup/$', TemplateView.as_view(template_name="signup.html"),
name='signup'),
Problem is as stated this:
File "/Desktop/zadnja/django-rest-auth/demo/demo/urls.py",
line 6, in
from views import home File "/Desktop/zadnja/django-rest-auth/demo/demo/views.py", line
2, in
from rest_auth.models import Upload, UploadForm ImportError: cannot import name Upload
You do not have circular imports since rest_auth/models.py does not import any component from demo/views.py
I'm assuming rest_auth is an app in you project. To import Upload and UploadForm you should use absolute import:
from project_name.rest_auth.models import Upload, UploadForm

How to accommodate APIView & ViewSet views in urls.py

How would one write a urls.py file to accommodate views created from APIView and ViewSet.
entity.views.py
from .models import Entity
from .serializers import EntitySerializer
class EntityViewSet(DefaultsMixin, ListCreateRetrieveUpdateViewSet):
"""
"""
queryset = Entity.objects.all()
serializer_class = EntitySerializer
filter_fields = ('id', 'entity_number')
class PersonProfileList(APIView):
"""
person profile
"""
def get(self, request, format=None):
pass
entity.urls.py
from django.conf.urls import url, include
from rest_framework.routers import DefaultRouter
from rest_framework.urlpatterns import format_suffix_patterns
from . import views
entity_router = DefaultRouter()
entity_router.register(r'entity', views.EntityViewSet)
urlpatterns = [
url(r'profile/$', views.PersonProfileList.as_view(), name='profile_list'), # Is this correct?
url(r'profile/(?P<pk>[0-9]+)/$', views.PersonProfileList.as_view(), name='profile_detail'),
]
urlpatterns = format_suffix_patterns(urlpatterns)
main urls.py
from django.conf.urls import include, url
from django.contrib import admin
from entities.urls import entity_router, urlpatterns
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^entities/', include(entity_router.urls)), #This I know works
url(r'^entities/', include(urlpatterns.url)), # This throws errors
]
What is the best way to accommodate both types of Views in the same URL file and have them appear under one /entity unlike now when am getting two /entity entries. Also, once I get into the /entity page in the browsable API, how do I make the /entity/profile viewable since now it only shows /entity. See images for guide.
Root Page
Entities Page

Best way to translate Django generic view

I am upgrading to Django 1.5 which has since deprecated generic views. I am using django-voting which used generic views. I am not sure how to translate this into a class based view:
from django.conf.urls.defaults import *
from django.views.generic.list_detail import object_list
from django.core.context_processors import request
from django.shortcuts import get_object_or_404, render_to_response
from blog.models import Blog
from voting.views import vote_on_object
from voting.models import Vote
import operator
urlpatterns = patterns('',
url(r'^links/(?P<object_id>\d+)/(?P<direction>up|down|clear)vote/?$',
vote_on_object,
dict(
model=Blog,
template_object_name='link',
template_name='blog/link_confirm_vote.html',
allow_xmlhttprequest=True,
),
name="link_vote",)
)
views.py
class BlogDetailView(DetailView):
model = Blog
template_name = 'idea/link_confirm_vote.html'
urls.py
from .views import BlogDetailView
urlpatterns = patterns('',
url(
regex=r'^links/(?P<object_id>\d+)/(?P<direction>up|down|clear)vote/?$',
view=BlogDetailView.as_view(),
name='link_vote'
),
)