AttributeError:' int'对象没有属性' start_time'

时间:2016-07-01 03:20:38

标签: django django-models django-forms django-views django-class-based-views

我的ChapterMarks中有models.py个类,其中包含来自Production类的外键。我正在尝试使用我在ChapterMarks views.py中提交的信息,以便用户可以继续进行剧集设置。在本节中,它要求用户可以在其播客中输入每个部分的开始时间,以便客户可以单击并将其带到某些时间戳。问题是我得到以下AttributeError

Environment:


Request Method: GET
Request URL: http://192.168.33.10:8000/fc/episodechaptermarks/

Django Version: 1.9
Python Version: 2.7.6
Installed Applications:
('producer',
 'django.contrib.admin',
 'django.contrib.sites',
 'registration',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'storages',
 'django_extensions',
 'randomslugfield',
 'adminsortable2',
 'crispy_forms')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'django.middleware.security.SecurityMiddleware')



Traceback:

File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
  149.                     response = self.process_exception_by_middleware(e, request)

File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
  147.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/usr/local/lib/python2.7/dist-packages/django/views/generic/base.py" in view
  68.             return self.dispatch(request, *args, **kwargs)

File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/mixins.py" in dispatch
  56.         return super(LoginRequiredMixin, self).dispatch(request, *args, **kwargs)

File "/usr/local/lib/python2.7/dist-packages/django/views/generic/base.py" in dispatch
  88.         return handler(request, *args, **kwargs)

File "/home/vagrant/fullcast_project/producer/views/views.py" in get
  738.             initial_values['start_time'] = chaptermark.start_time

Exception Type: AttributeError at /fc/episodechaptermarks/
Exception Value: 'int' object has no attribute 'start_time'

错误位于get的{​​{1}}课程中的ChapterMarks方法下: views.py

欢迎任何建议

以下是initial_values['start_time'] = chaptermark.start_time中的ChapterMarks课程:

views.py
我的class EpisodeChapterMarksView(LoginRequiredMixin, View): form_class = EpisodeChapterMarksForm template_name = 'fc/forms_chapter_marks.html' def get(self, request, *args, **kwargs): initial_values = {} user = request.user client, podcast = get_fc_client_and_podcast_for_user(user) if client is None or podcast is None: raise Http404 production = Production.objects.filter(podcast=podcast).first() if production is None: raise Http404 initial_values['production_id'] = production.id chaptermark_id = production.id if chaptermark_id is not None: chaptermark = production.id initial_values['chaptermark_id'] = chaptermark_id initial_values['start_time'] = chaptermark.start_time initial_values['title'] = chaptermark.title form = self.form_class(initial=initial_values) return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) client, podcast = get_fc_client_and_podcast_for_user(request.user) if form.is_valid(): # lets get the data production_id = form.cleaned_data.get('production_id') chaptermark_id = form.cleaned_data.get('chaptermark_id') start_time = form.cleaned_data.get('start_time') title = form.cleaned_data.get('title') # Get production production = get_object_or_404(Production, id=production_id) # if a chaptermark existed, we update, if not we create if chaptermark_id is not None: chaptermark = ChapterMark.objects.get(id=chaptermark_id) else: chaptermark = ChapterMark() chaptermark.start_time = start_time chaptermark.title = title chaptermark.save() production.chapter_mark = chaptermark production.save() # TODO: Needs to redirect to next step return HttpResponseRedirect(reverse('fc:episodeshowlinks')) return render(request, self.template_name, {'form': form}) 中的

ProductionChapterMark课程:

models.py

-------------------------------------------- -----

    class Production(TimeStampedModel):
    BASE_PRODUCTION = 'B'
    SECONDARY_PRODUCTION = 'S'

    podcast = models.ForeignKey(Podcast, on_delete=models.SET_NULL, null=True)
    ready_for_production = models.BooleanField(default=False)

    episode_number = models.PositiveIntegerField(null=True)
    episode_title = models.CharField(max_length=255)
    episode_guest_last_name = models.CharField(max_length=128, null=True, blank=True)
    episode_guest_first_name = models.CharField(max_length=128, null=True, blank=True)
    episode_guest_twitter_name = models.CharField(max_length=64, null=True, blank=True)
    episode_summary = models.TextField(blank=False, null=True)

    base_production_uuid = models.CharField(max_length=32, null=True, blank=True)
    base_production_status = models.CharField(max_length=255, blank=True)
    base_production_produced = models.BooleanField(default=False)
    base_production_started = models.BooleanField(default=False)
    base_production_cover_image = models.CharField(max_length=255, null=True)
    square_image_file = models.FileField(null=True, blank=True)

    secondary_production_uuid = models.CharField(max_length=32, null=True, blank=True)
    secondary_production_status = models.CharField(max_length=255, blank=True)
    secondary_production_produced = models.BooleanField(default=False)
    secondary_production_started = models.BooleanField(default=False)
    secondary_production_cover_image = models.CharField(max_length=255, null=True)
    banner_image_file = models.FileField(null=True, blank=True)

    auphonic_result_url = models.URLField(null=True, blank=True)
    soundcloud_result_url = models.URLField(null=True, blank=True)
    youtube_result_url = models.URLField(null=True, blank=True)
    libsyn_result_url = models.URLField(null=True, blank=True)
    spreaker_result_id = models.PositiveIntegerField(null=True)
    spreaker_result_id_request_attempted = models.BooleanField(default=False)

    source_file_name = models.CharField(max_length=64, null=True)
    source_file_image = models.FileField(null=True, blank=True)
    output_base_name = models.CharField(max_length=64, null=True)

    scheduled_date = models.DateTimeField(null=True, blank=True)
    fully_produced_date = models.DateTimeField(null=True, blank=True)
    auto_email_sent = models.BooleanField(default=False)

    post_to_wordpress = models.BooleanField(default=True)
    wordpress_post_id = models.PositiveIntegerField(null=True)
    wordpress_slug = models.CharField(max_length=127, null=True, blank=True)
    wordpress_url = models.URLField(null=True, blank=True)
    wordpress_short_url = models.URLField(null=True, blank=True)
    wordpress_featured_image = models.CharField(max_length=255, null=True, blank=True)
    wordpress_featured_image_upload = models.FileField(null=True, blank=True)
    wordpress_post_unique_tags = models.TextField(null=True, blank=True)
    wordpress_posting_failure_notified = models.BooleanField(default=False)

    transcription_url = models.URLField(null=True, blank=True)

    tweets_already_scheduled = models.BooleanField(default=False)
    number_of_refresh_tweets = models.PositiveIntegerField(default=0)
    tweets_scheduling_failure_notified = models.BooleanField(default=False)

    def __unicode__(self):
        return smart_text(self.base_production_episode_title())

    def fully_produced(self):
        return self.base_production_produced and self.secondary_production_produced
    fully_produced.short_description = 'Produced'

    def status(self):
        if not self.fully_produced():
            return 'Pending'
        if self.wordpress_url:
            return 'Published'
        return 'Produced'

    def episode(self):
        return self.episode_number

    def base_production_episode_title(self):
        return self._title_string_for_format(self.podcast.base_production_name_format)

    def secondary_production_episode_title(self):
        return self._title_string_for_format(self.podcast.secondary_production_name_format)

    def _title_string_for_format(self, title_format):
        from producer.helpers import replace_placeholder_in_text_format_with_parameter

        guest_name = self.episode_guest()
        episode_number = str(self.episode_number).zfill(3)
        episode_title = self.episode_title

        title = replace_placeholder_in_text_format_with_parameter(title_format, 'EPISODE_GUEST_FULL_NAME', guest_name)
        title = replace_placeholder_in_text_format_with_parameter(title, 'EPISODE_NUMBER', episode_number)
        title = replace_placeholder_in_text_format_with_parameter(title, 'EPISODE_TITLE', episode_title)

        return title

    def episode_guest(self):
        if self.episode_guest_last_name and self.episode_guest_first_name:
            return '%s %s' % (self.episode_guest_first_name, self.episode_guest_last_name)

        if self.episode_guest_last_name:
            return self.episode_guest_last_name

        if self.episode_guest_first_name:
            return self.episode_guest_first_name

        return ''

class ChapterMark(TimeStampedModel): production = models.ForeignKey(Production) start_time = models.TimeField() title = models.CharField(max_length=200) url = models.URLField(blank=True) image_name = models.CharField(max_length=60, blank=True) def start_time_string(self): return self.start_time.strftime('%H:%M:%S') def wordpress_start_time_string(self): string = self.chapter_timestamp() return string if string else '-:-' def link(self): if self.url: return '<a href="%s" target="_blank">%s</a>' % (self.url, self.url) return link.allow_tags = True def __unicode__(self): return u'' def chapter_timestamp(self): if self.start_time: if self.start_time.hour > 0: return self.start_time.strftime('%H:%M:%S') return self.start_time.strftime('%M:%S') return 表格

chapter_marks.py

------------- ------------- UPDATE

新错误:

from django import forms

class EpisodeChapterMarksForm(forms.Form):

    production_id = forms.IntegerField(widget=forms.Field.hidden_widget, required=False)

    id = forms.IntegerField(widget=forms.Field.hidden_widget)

    chaptermark_id = forms.IntegerField(widget=forms.Field.hidden_widget, required=False)
    start_time = forms.TimeField()
    title = forms.CharField(max_length=200)

3 个答案:

答案 0 :(得分:0)

更改

chaptermark = production.chapter_mark

chaptermark = production.chaptermark_set.get(id=chaptermark_id)

答案 1 :(得分:0)

在doniyor版本中你必须制作

chaptermark = production.chaptermark_set.get(id=chaptermark_id) 
chaptermark.start_time 

你将获得价值。 如果您想在start_time的一个步骤中获得价值,可以尝试

chaptermark = production.chaptermark_set.values('start_time')[0]['start_time']

请注意,第二个属性 - “title”

也存在同样的问题

答案 2 :(得分:0)

让我们尝试理解您的代码:

def get(self, request, *args, **kwargs):
    initial_values = {}
    user = request.user

    client, podcast = get_fc_client_and_podcast_for_user(user)
    if client is None or podcast is None:
        raise Http404

到目前为止一直很好......

    production = Production.objects.filter(podcast=podcast).first()

这很奇怪,为什么你会为特定播客选择第一个Production ...如果你有1对1,那么如果你有1对多就使用OneToOneField - 应该是一个限制选择Production的东西,或者你应该返回一个附加到播客的所有Production的列表 - 所以这里有一些不稳定的

    if production is None:
         raise Http404
好的,但是有魔法&#34; get_object_or_404捷径......

    initial_values['production_id'] = production.id
    chaptermark_id = production.id

    if chaptermark_id is not None:
        chaptermark = production.id

好的......您正在为int

分配chaptermark
        initial_values['chaptermark_id'] = chaptermark_id
        initial_values['start_time'] = chaptermark.start_time
        initial_values['title'] = chaptermark.title

这两行试图获取chaptermark的属性,但chaptermark不是您的模型对象,而是int - 它没有这些属性!

所以看起来您应该(稍早)将chaptermark的{​​{1}}分配给ChapterMark,但是...... Production可能有多个ChapterMark ... 你希望看到ChapterMark哪个?

这看起来像另一个严重的流程,因为你在这里有1对多,这可以在Form中表示,但作为依赖FormSet - 与章节列表-marks。

因此,您的方法存在根本性错误!