加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

django – 无法通过泛型类视图将’slug’字段传递到URL

发布时间:2020-12-20 11:19:43 所属栏目:Python 来源:网络整理
导读:我有两个出版物和员工模型: class Publication(models.Model): BOOK_CHAPTER = 1 ARTICLE = 2 PUBLICATION_CHOICES = ( (BOOK_CHAPTER,'Book chapter'),(ARTICLE,'Article'),) publication_type = models.IntegerField(choices=PUBLICATION_CHOICES) articl
我有两个出版物和员工模型:

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,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,blank=True)
    location_of_publication = models.CharField(max_length=250,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,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.",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,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()),)

但是我在/ employees / joe-reporter / publications /得到一个IndexError,因为元组索引超出了范围.这是追溯:

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,**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

我究竟做错了什么?

解决方法

由于您在urlpattern正则表达式中使用了一个命名组,因此slug作为关键字参数传递,而不是位置参数.所以你从self.kwargs [‘slug’]而不是self.args [0]得到它.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读