我在理解新CBV如何工作方面遇到了一些麻烦.我的问题是,我需要登录所有视图,其中一些是特定权限.在基于函数的视图中,我使用@permission_required()和视图中的login_required属性执行此操作,但我不知道如何在新视图上执行此操作.django文档中是否有一些部分解释了这一点?我没找到任何东西.我的代码有什么问题?
我尝试使用@method_decorator,但它回复" / errors/prueba/_wrapped_view()中的TypeError至少需要1个参数(0给定) "
这是代码(GPL):
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required, permission_required
class ViewSpaceIndex(DetailView):
"""
Show the index page of a space. Get various extra contexts to get the
information for that space.
The get_object method searches in the user 'spaces' field if the current
space is allowed, if not, he is redirected to a 'nor allowed' page.
"""
context_object_name = 'get_place'
template_name = 'spaces/space_index.html'
@method_decorator(login_required)
def get_object(self):
space_name = self.kwargs['space_name']
for i in self.request.user.profile.spaces.all():
if i.url …Run Code Online (Sandbox Code Playgroud) django django-views django-authentication django-class-based-views class-based-views
我不清楚在Django 1.5中如何最好地访问基于类的视图中的URL参数.
考虑以下:
视图:
from django.views.generic.base import TemplateView
class Yearly(TemplateView):
template_name = "calendars/yearly.html"
current_year = datetime.datetime.now().year
current_month = datetime.datetime.now().month
def get_context_data(self, **kwargs):
context = super(Yearly, self).get_context_data(**kwargs)
context['current_year'] = self.current_year
context['current_month'] = self.current_month
return context
Run Code Online (Sandbox Code Playgroud)
URL配置:
from .views import Yearly
urlpatterns = patterns('',
url(
regex=r'^(?P<year>\d+)/$',
view=Yearly.as_view(),
name='yearly-view'
),
)
Run Code Online (Sandbox Code Playgroud)
我想year在我的视图中访问参数,所以我可以像以下那样执行逻辑:
month_names = [
"January", "February", "March", "April",
"May", "June", "July", "August",
"September", "October", "November", "December"
]
for month, month_name in enumerate(month_names, start=1):
is_current = False
if year == current_year …Run Code Online (Sandbox Code Playgroud) 我今天读到Django 1.3 alpha正在发售,最引人注目的新功能是引入基于类的视图.
我已经阅读了相关的文档,但我发现很难看到使用它们可以获得的大优势,所以我在这里要求一些帮助来理解它们.
让我们从文档中获取一个高级示例.
from books.views import PublisherBookListView
urlpatterns = patterns('',
(r'^books/(\w+)/$', PublisherBookListView.as_view()),
)
Run Code Online (Sandbox Code Playgroud)
from django.shortcuts import get_object_or_404
from django.views.generic import ListView
from books.models import Book, Publisher
class PublisherBookListView(ListView):
context_object_name = "book_list"
template_name = "books/books_by_publisher.html",
def get_queryset(self):
self.publisher = get_object_or_404(Publisher, name__iexact=self.args[0])
return Book.objects.filter(publisher=self.publisher)
def get_context_data(self, **kwargs):
# Call the base implementation first to get a context
context = super(PublisherBookListView, self).get_context_data(**kwargs)
# Add in the publisher
context['publisher'] = self.publisher
return …Run Code Online (Sandbox Code Playgroud) 我有以下代码来序列化查询集;
def render_to_response(self, context, **response_kwargs):
return HttpResponse(json.simplejson.dumps(list(self.get_queryset())),
mimetype="application/json")
Run Code Online (Sandbox Code Playgroud)
以下是我的 get_querset()
[{'product': <Product: hederello ()>, u'_id': u'9802', u'_source': {u'code': u'23981', u'facilities': [{u'facility': {u'name': {u'fr': u'G\xe9n\xe9ral', u'en': u'General'}, u'value': {u'fr': [u'bar', u'r\xe9ception ouverte 24h/24', u'chambres non-fumeurs', u'chambres familiales',.........]}]
Run Code Online (Sandbox Code Playgroud)
我需要序列化.但它说不能序列化<Product: hederello ()>.因为列表由django对象和dicts组成.有任何想法吗 ?
我有以下型号:
class Bill(models.Model):
date = models.DateTimeField(_("Date of bill"),null=True,blank=True)
class Item(models.Model):
name = models.CharField(_("Name"),max_length=100)
price = models.FloatField(_("Price"))
quantity = models.IntegerField(_("Quantity"))
bill = models.ForeignKey("Bill",verbose_name=_("Bill"),
related_name="billitem")
Run Code Online (Sandbox Code Playgroud)
我知道这是可能的:
from django.forms.models import inlineformset_factory
inlineformset_factory(Bill, Item)
Run Code Online (Sandbox Code Playgroud)
然后通过标准视图处理.
现在我想知道,如果有一种方法可以实现相同的(意思是:使用内联来添加/编辑属于账单的项目)使用基于类的视图(而不是管理界面).
有谁知道或者任何人都可以生成Django基于类的通用DeleteView的简单示例?我想子类化DeleteView并确保当前登录的用户在删除之前拥有该对象的所有权.任何帮助将非常感谢.先感谢您.
我正在使用通用的CreateView,如:
#urls.py
from django.conf.urls.defaults import *
from django.views.generic import CreateView
from content.models import myModel
urlpatterns = patterns('myApp.views',
(r'myCreate/$', CreateView.as_view(model=myModel)),
)
Run Code Online (Sandbox Code Playgroud)
使用mymodel_form.html模板,例如:
<form method="post" action="">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
Run Code Online (Sandbox Code Playgroud)
当我提交表单时,会创建新对象但我收到错误
在...处配置不当
没有要重定向到的网址.在模型上提供url或定义get_absolute_url方法.
如何指定成功重定向的URL?
说,我有以下mixin通过触摸相互重叠dispatch():
class FooMixin(object):
def dispatch(self, *args, **kwargs):
# perform check A
...
return super(FooMixin, self).dispatch(*args, **kwargs)
class BarMixin(object):
def dispatch(self, *args, **kwargs):
# perform check B
...
return super(FooMixin, self).dispatch(*args, **kwargs)
Run Code Online (Sandbox Code Playgroud)
如果我希望我的视图通过订单,请检查A - >检查B,如果我的代码是MyView(FooMixin, BarMixin, View)或者MyView(BarMixin, FooMixin, View)?
为什么我们总是View在mixins之后放入或者它的子类?(我从阅读django通用视图的源代码中注意到了这一点,但我不知道它背后的基本原理,如果有的话)
python django django-views method-resolution-order django-class-based-views
我正在按照我的urlpatterns所在的教程:
urlpatterns = patterns('',
url(r'^passwords/$', PasswordListView.as_view(), name='passwords_api_root'),
url(r'^passwords/(?P<id>[0-9]+)$', PasswordInstanceView.as_view(), name='passwords_api_instance'),
...other urls here...,
)
Run Code Online (Sandbox Code Playgroud)
该PasswordListView和PasswordInstanceView应该是基于类的观点.我无法弄清楚name参数的含义.它是传递给视图的默认参数吗?
我有一个模特:
class Article(models.Model):
text = models.CharField()
author = models.ForeignKey(User)
Run Code Online (Sandbox Code Playgroud)
如何编写基于类的视图来创建新模型实例并将author外键设置为request.user?
更新:
解决方案转到下面单独的答案.