Best way to translate Django generic view - django

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'
),
)

Related

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.

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

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'),

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

Custom template in django form wizard - NameError

I am trying to create custom templates for a simple contact form as per the django docs but I am getting a NameError. Looks like a simple issue but I can't figure it out. Any help will be greatly appreciated. The error message is:
"NameError at /contact/
name 'wizardcustomtemplate' is not defined"
where 'wizardcustomtemplate' is the app. Here is my code:
urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
from wizardcustomtemplate.forms import SubjectForm, SenderForm, MessageForm
from wizardcustomtemplate.views import ContactWizard
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^contact/$', ContactWizard.as_view(FORMS)),
)
views.py
import os
from django.shortcuts import render
from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.core.mail import send_mail
from django.core.context_processors import csrf
from django.contrib.formtools.wizard.views import SessionWizardView
from django.contrib.formtools.wizard.views import WizardView
from django.core.files.storage import FileSystemStorage
from django.core.files import File
FORMS = [("0", wizardcustomtemplate.forms.SubjectForm),
("1", wizardcustomtemplate.forms.SenderForm),
("2", wizardcustomtemplate.forms.MessageForm)
]
TEMPLATES = {"0": "wizardcustomtemplate/subject.html",
"1": "wizardcustomtemplate/sender.html",
"2": "wizardcustomtemplate/message.html"
}
class ContactWizard(SessionWizardView):
def get_template_names(self):
return [TEMPLATES[self.steps.current]]
def done(self, form_list, **kwargs):
form_data = process_form_data(form_list)
return render_to_response('wizardcustomtemplate/thanks.html', {'form_data': form_data})
def process_form_data(form_list):
form_data = [form.cleaned_data for form in form_list]
return form_data
forms.py
from django import forms
class SubjectForm(forms.Form):
subject = forms.CharField(max_length = 100,initial='Wizard')
class SenderForm(forms.Form):
sender = forms.EmailField(initial='abcd#efgh.org')
class MessageForm(forms.Form):
message = forms.CharField(initial='How r u?')
The form wizard works fine if I don't use the custom templates (FORMS, TEMPLATES etc.) Please let me know if you need additional information.
Solved it by adding import wizardcustomtemplate in views.py as suggested by #Rohan.