无法通过“蛞蝓”通过通用类视图将字段放入 URL

发布于 11-27 04:02 字数 7771 浏览 1 评论 0原文

我有两个出版物和员工模型:

class Publication(models.Model):
    BOOK_CHAPTER = 1
    ARTICLE = 2
    PUBLICATION_CHOICES = (
        (BOOK_CHAPTER, 'Book chapter'),
        (ARTICLE, 'Article'),
    )
    publication_type = models.IntegerField(choices=PUBLICATION_CHOICES)
    article_title = models.CharField(max_length=250, help_text='Limited to 250 characters. May also be used for book chapter titles.')
    slug = models.SlugField(help_text='Suggested value automatically generated from title.')
    primary_author = models.ForeignKey('Employee', limit_choices_to={'employee_type': 1}, help_text='Most of the time, this will be the faculty member to whom the publication is tied.')
    authors = models.CharField(max_length=250, help_text='Limited to 250 characters. Please adhere to accepted format for style. Include current employee in this list.', blank=True)
    journal_name = models.CharField(max_length=250, help_text='Limited to 250 characters. May also be used for book titles.')
    journal_volume = models.IntegerField(max_length=3, blank=True, null=True)
journal_issue = models.IntegerField(max_length=3, blank=True, null=True)
    journal_pub_date = models.DateField(help_text='To specify only the year, simply type in the date using the following format: 2011-01-01.')
    journal_page_range = models.CharField(max_length=50, help_text='Limited to 50 characters.', blank=True)
    editors = models.CharField(max_length=250, help_text='Limited to 250 characters.', blank=True)
    publisher = models.CharField(max_length=250, help_text='Limited to 250 characters.', blank=True)
    location_of_publication = models.CharField(max_length=250, help_text='Limited to 250 characters.', blank=True)
    abstract = models.TextField(blank=True)
    notes = models.TextField(blank=True)
    external_link = models.URLField(blank=True, help_text='Link to the article on the publication\'s website.')
    downloadable_version = models.ForeignKey(Document, blank=True, null=True)

并且:

class Employee(models.Model):
    FACULTY = 1
    ADMINISTRATIVE_SUPPORT = 2
    RESEARCH_SUPPORT = 3
    POSTDOCS = 4
    EMPLOYEE_CHOICES = (
        (FACULTY, 'Faculty'),
        (ADMINISTRATIVE_SUPPORT, 'Administrative support'),
        (RESEARCH_SUPPORT, 'Research support'),
        (POSTDOCS, 'Postdocs'),
    )
    user = models.ForeignKey(User, unique=True, help_text="Select a user if this employee is able to update their own profile information.", blank=True, null=True)

    first_name = models.CharField(max_length=200)
    middle_name = models.CharField(max_length=50, help_text="Limited to 50 characters.", blank=True)
    last_name = models.CharField(max_length=200)

    slug = models.SlugField(unique=True, help_text='Will populate from a combination of the first, middle and last names.')

    title = models.CharField(max_length=200, help_text="Limited to 200 characters.")
    previous_position = models.CharField(max_length=350, help_text="Limited to 350 characters.", blank=True)

    email = models.EmailField()
    office_phone_number = PhoneNumberField(null=True, blank=True)
    mobile_phone_number = PhoneNumberField(null=True, blank=True)
    office = models.CharField(max_length=50, help_text="Your office number or room name. Limited to 50 characters.", blank=True)
    website = models.URLField(blank=True)

    job_description = models.TextField(help_text='A description of your work or research. No HTML is allowed. If formatting is needed, please use <a href="http://daringfireball.net/projects/markdown/syntax">Markdown syntax</a>.', blank=True)
    job_description_html = models.TextField(blank=True, editable=False)

    job_description_summary = models.CharField(max_length=250, help_text="A brief summary of your work or research. Limited to 250 characters.")

    is_currently_employed = models.BooleanField(default=True)
    related_links = generic.GenericRelation(RelatedLink, blank=True)
    employee_type = models.IntegerField(choices=EMPLOYEE_CHOICES)

    photo = models.ImageField(upload_to='images/profiles/mugshots', blank=True)
    lead_image = models.ImageField(upload_to='images/profiles/graphics', blank=True)

    resume_or_cv = models.ForeignKey(Document, blank=True, null=True)

    sites = models.ManyToManyField(Site)

我希望有一个视图来显示员工的所有出版物。这是我现在正在使用的视图:

from django.shortcuts import get_object_or_404
from django.views.generic import ListView
from cms.employees.models import Employee, Publication

class EmployeePublicationsListView(ListView):

    context_object_name = "publication_list"
    template_name = "employees/publications_by_employee.html",

    def get_queryset(self):
        self.primary_author = get_object_or_404(Employee, slug__iexact=self.args[0])
        return Publication.objects.filter(primary_author=self.primary_author)

    def get_context_data(self, **kwargs):
        context = super(EmployeePublicationsListView, self).get_context_data(**kwargs)
        context['primary_author'] = self.primary_author
        return context

这是我当前正在使用的 URL 模式,我将 Employee 模型中的 slug 传递到 URL 中,以获取该员工的所有出版物的列表:

from django.conf.urls.defaults import patterns, include, url
from cms.employees.models import Employee, Publication
from django.views.generic import ListView, DetailView
from cms.employees.views import EmployeePublicationsListView, EmployeeMentionsListView

urlpatterns = patterns('',
    (r'^(?P<slug>[-\w]+)/publications/$', EmployeePublicationsListView.as_view()),

)

但我收到了 IndexError在 /employees/joe-reporter/publications/ 处,元组索引超出范围。这是回溯:

Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/employees/joe-reporter/publications/

Django Version: 1.3
Python Version: 2.6.1
Installed Applications:
['django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.flatpages',
 'django.contrib.admin',
 'django.contrib.admindocs',
 'django.contrib.sitemaps',
 'django.contrib.humanize',
 'django.contrib.redirects',
 'django.contrib.webdesign',
 'cms.news',
 'cms.media',
 'cms.categories',
 'cms.related_links',
 'cms.employees',
 'cms.static_media',
 'cms.places',
 'cms.events',
 'cms.jobs',
 'cms.press',
 'cms.topics',
 'cms.featured',
 'tagging',
 'template_utils',
 'contact_form',
 'cms.research',
 'shorturls']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.contrib.redirects.middleware.RedirectFallbackMiddleware')


Traceback:
File "/Library/Python/2.6/site-packages/django/core/handlers/base.py" in get_response
  111.                         response = callback(request, *callback_args, **callback_kwargs)
File "/Library/Python/2.6/site-packages/django/views/generic/base.py" in view
  47.             return self.dispatch(request, *args, **kwargs)
File "/Library/Python/2.6/site-packages/django/views/generic/base.py" in dispatch
  68.         return handler(request, *args, **kwargs)
File "/Library/Python/2.6/site-packages/django/views/generic/list.py" in get
  116.         self.object_list = self.get_queryset()
File "/Users/pbeeson/Sites/django_projects/cms/../cms/employees/views.py" in get_queryset
  16.         self.primary_author = get_object_or_404(Employee, slug__iexact=self.args[0])

Exception Type: IndexError at /employees/joe-reporter/publications/
Exception Value: tuple index out of range

我做错了什么?

I have two models for Publications and Employees:

class Publication(models.Model):
    BOOK_CHAPTER = 1
    ARTICLE = 2
    PUBLICATION_CHOICES = (
        (BOOK_CHAPTER, 'Book chapter'),
        (ARTICLE, 'Article'),
    )
    publication_type = models.IntegerField(choices=PUBLICATION_CHOICES)
    article_title = models.CharField(max_length=250, help_text='Limited to 250 characters. May also be used for book chapter titles.')
    slug = models.SlugField(help_text='Suggested value automatically generated from title.')
    primary_author = models.ForeignKey('Employee', limit_choices_to={'employee_type': 1}, help_text='Most of the time, this will be the faculty member to whom the publication is tied.')
    authors = models.CharField(max_length=250, help_text='Limited to 250 characters. Please adhere to accepted format for style. Include current employee in this list.', blank=True)
    journal_name = models.CharField(max_length=250, help_text='Limited to 250 characters. May also be used for book titles.')
    journal_volume = models.IntegerField(max_length=3, blank=True, null=True)
journal_issue = models.IntegerField(max_length=3, blank=True, null=True)
    journal_pub_date = models.DateField(help_text='To specify only the year, simply type in the date using the following format: 2011-01-01.')
    journal_page_range = models.CharField(max_length=50, help_text='Limited to 50 characters.', blank=True)
    editors = models.CharField(max_length=250, help_text='Limited to 250 characters.', blank=True)
    publisher = models.CharField(max_length=250, help_text='Limited to 250 characters.', blank=True)
    location_of_publication = models.CharField(max_length=250, help_text='Limited to 250 characters.', blank=True)
    abstract = models.TextField(blank=True)
    notes = models.TextField(blank=True)
    external_link = models.URLField(blank=True, help_text='Link to the article on the publication\'s website.')
    downloadable_version = models.ForeignKey(Document, blank=True, null=True)

And:

class Employee(models.Model):
    FACULTY = 1
    ADMINISTRATIVE_SUPPORT = 2
    RESEARCH_SUPPORT = 3
    POSTDOCS = 4
    EMPLOYEE_CHOICES = (
        (FACULTY, 'Faculty'),
        (ADMINISTRATIVE_SUPPORT, 'Administrative support'),
        (RESEARCH_SUPPORT, 'Research support'),
        (POSTDOCS, 'Postdocs'),
    )
    user = models.ForeignKey(User, unique=True, help_text="Select a user if this employee is able to update their own profile information.", blank=True, null=True)

    first_name = models.CharField(max_length=200)
    middle_name = models.CharField(max_length=50, help_text="Limited to 50 characters.", blank=True)
    last_name = models.CharField(max_length=200)

    slug = models.SlugField(unique=True, help_text='Will populate from a combination of the first, middle and last names.')

    title = models.CharField(max_length=200, help_text="Limited to 200 characters.")
    previous_position = models.CharField(max_length=350, help_text="Limited to 350 characters.", blank=True)

    email = models.EmailField()
    office_phone_number = PhoneNumberField(null=True, blank=True)
    mobile_phone_number = PhoneNumberField(null=True, blank=True)
    office = models.CharField(max_length=50, help_text="Your office number or room name. Limited to 50 characters.", blank=True)
    website = models.URLField(blank=True)

    job_description = models.TextField(help_text='A description of your work or research. No HTML is allowed. If formatting is needed, please use <a href="http://daringfireball.net/projects/markdown/syntax">Markdown syntax</a>.', blank=True)
    job_description_html = models.TextField(blank=True, editable=False)

    job_description_summary = models.CharField(max_length=250, help_text="A brief summary of your work or research. Limited to 250 characters.")

    is_currently_employed = models.BooleanField(default=True)
    related_links = generic.GenericRelation(RelatedLink, blank=True)
    employee_type = models.IntegerField(choices=EMPLOYEE_CHOICES)

    photo = models.ImageField(upload_to='images/profiles/mugshots', blank=True)
    lead_image = models.ImageField(upload_to='images/profiles/graphics', blank=True)

    resume_or_cv = models.ForeignKey(Document, blank=True, null=True)

    sites = models.ManyToManyField(Site)

I'd like to have a view to display all publications for an employee. Here's the view I'm working with now:

from django.shortcuts import get_object_or_404
from django.views.generic import ListView
from cms.employees.models import Employee, Publication

class EmployeePublicationsListView(ListView):

    context_object_name = "publication_list"
    template_name = "employees/publications_by_employee.html",

    def get_queryset(self):
        self.primary_author = get_object_or_404(Employee, slug__iexact=self.args[0])
        return Publication.objects.filter(primary_author=self.primary_author)

    def get_context_data(self, **kwargs):
        context = super(EmployeePublicationsListView, self).get_context_data(**kwargs)
        context['primary_author'] = self.primary_author
        return context

Here's the URL pattern I'm using currently where I'm passing the slug from the Employee model into the URL for a list of all publications by that employee:

from django.conf.urls.defaults import patterns, include, url
from cms.employees.models import Employee, Publication
from django.views.generic import ListView, DetailView
from cms.employees.views import EmployeePublicationsListView, EmployeeMentionsListView

urlpatterns = patterns('',
    (r'^(?P<slug>[-\w]+)/publications/

But I'm getting a IndexError at /employees/joe-reporter/publications/ for tuple index out of range. Here's the traceback:

Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/employees/joe-reporter/publications/

Django Version: 1.3
Python Version: 2.6.1
Installed Applications:
['django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.flatpages',
 'django.contrib.admin',
 'django.contrib.admindocs',
 'django.contrib.sitemaps',
 'django.contrib.humanize',
 'django.contrib.redirects',
 'django.contrib.webdesign',
 'cms.news',
 'cms.media',
 'cms.categories',
 'cms.related_links',
 'cms.employees',
 'cms.static_media',
 'cms.places',
 'cms.events',
 'cms.jobs',
 'cms.press',
 'cms.topics',
 'cms.featured',
 'tagging',
 'template_utils',
 'contact_form',
 'cms.research',
 'shorturls']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.contrib.redirects.middleware.RedirectFallbackMiddleware')


Traceback:
File "/Library/Python/2.6/site-packages/django/core/handlers/base.py" in get_response
  111.                         response = callback(request, *callback_args, **callback_kwargs)
File "/Library/Python/2.6/site-packages/django/views/generic/base.py" in view
  47.             return self.dispatch(request, *args, **kwargs)
File "/Library/Python/2.6/site-packages/django/views/generic/base.py" in dispatch
  68.         return handler(request, *args, **kwargs)
File "/Library/Python/2.6/site-packages/django/views/generic/list.py" in get
  116.         self.object_list = self.get_queryset()
File "/Users/pbeeson/Sites/django_projects/cms/../cms/employees/views.py" in get_queryset
  16.         self.primary_author = get_object_or_404(Employee, slug__iexact=self.args[0])

Exception Type: IndexError at /employees/joe-reporter/publications/
Exception Value: tuple index out of range

What am I doing wrong?

, EmployeePublicationsListView.as_view()), )

But I'm getting a IndexError at /employees/joe-reporter/publications/ for tuple index out of range. Here's the traceback:

What am I doing wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

甜心小果奶2024-12-04 04:02:35

由于您在 urlpattern 正则表达式中使用命名组,因此 slug 作为关键字参数而不是位置参数传递。因此,您可以从 self.kwargs['slug'] 而不是 self.args[0] 获取它。

Since you are using a named group in your urlpattern regex, the slug is passed as a keyword argument, not a positional argument. So you get it from self.kwargs['slug'] rather than self.args[0].

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文