繁体   English   中英

Django:AttributeError-对象没有属性

[英]Django: AttributeError - Object has no attribute

该视图抛出AttributeError:“ PhotoForm”对象没有属性“ reservation”。 会发生什么—函数通过,但实际上并未上传图像。 在调试它时, 该表格无效。

我尝试打印

  • 形式保留
  • 表格消息
  • 形式照片

但这显示了这种追溯(这就是表单无效和未完成功能的原因。

当我从其他正在运行的功能中构建这个功能时,我有些困惑。 谢谢您的帮助!

HTML表格

<form action="/photo/new/" method="post">{% csrf_token %}
    <dl>
        <dt>{{ form.reservation.label }}</dt>
            <dd><select name="reservation"> {% for reservation in reservations %} <option value="{{reservation.id}}">{{reservation.date}} {{reservation.chef.cook.get_profile.firstname}} - {{reservation.guest.get_profile.firstname}}</option>{% endfor %}</select></dd>
        <dt>{{ form.photo.label }}</dt>
            <dd>{{ form.photo }}</dd>
        <dt> {{ form.message.label }}</dt>
            <dd>{{ form.message }}</dd>
    </dl>
<button type="submit">Submit</button>
</form>

风景

@login_required
def new_photo(request, template_name="photo/newphoto.html"):

  meals = Reservation.objects.filter(guest=request.user.id)
  form = PhotoForm(request.POST)
  form.data = { "reservations": meals }
  if request.method == 'POST':
    form.photographer = request.user
    form.data.get('reservation')
    print form.reservation
    print form.message
    print form.photo
    if form.is_valid():
      print" hellos"
      save_reservation_photo(request.FILES["photo"])
      photo = form.save(commit=False)
      photo.photographer = request.user
      photo.save()
      return HttpResponseRedirect('/photo/%d/' % photo.id )
  else:
    form = PhotoForm()

  data = {'form':form,'reservations':meals,
    'add':True
  }

  return render_to_response(template_name,
                            data,
                            context_instance=RequestContext(request))

表格:

class PhotoForm(forms.ModelForm):
  class Meta:
    model = Photo
    fields = ('reservation','photo','message')

  def __init__(self, *args, **kwargs):
      super(PhotoForm, self).__init__(*args, **kwargs)

该模型:

class Photo(models.Model):

  photographer = models.ForeignKey(User)
  pub_date = models.DateTimeField(default=datetime.now,auto_now_add=True,db_index=True)
  reservation = models.ForeignKey(Reservation)

  message = models.CharField(default='',max_length=140)

  photo = models.ImageField(default='',upload_to="reservation_images/")

追溯

Traceback:
Environment:

Request Method: POST
Request URL: http://127.0.0.1:8000/photo/new/
Django Version: 1.2.3
Python Version: 2.7.0
Installed Applications:
['django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.messages',
 'django.contrib.comments',
 'django.contrib.markup',
 'django.contrib.sitemaps',
 'lib.debug_toolbar',
 'src',
 'django.contrib.admin']
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',
 'lib.debug_toolbar.middleware.DebugToolbarMiddleware')


Traceback:

Environment:

Request Method: POST
Request URL: http://127.0.0.1:8000/photo/new/
Django Version: 1.2.3
Python Version: 2.7.0
Installed Applications:
['django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.messages',
 'django.contrib.comments',
 'django.contrib.markup',
 'django.contrib.sitemaps',
 'lib.debug_toolbar',
 'src',
 'django.contrib.admin']
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',
 'lib.debug_toolbar.middleware.DebugToolbarMiddleware')


Traceback:
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  100.                     response = callback(request, *callback_args, **callback_kwargs)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
  25.                 return view_func(request, *args, **kwargs)
File "/Users/emilepetrone/Sites/meal/../meal/src/views.py" in new_photo
  532.     print form.reservation

Exception Type: AttributeError at /photo/new/
Exception Value: 'PhotoForm' object has no attribute 'reservation'

不应使用request.FILES初始化表单(带有图像或文件字段)吗?

form = PhotoForm(request.POST, request.FILES)

关键在于表单中有files = request.FILES。

@login_required
def new_photo(request, template_name="photo/newphoto.html"):

  form = PhotoForm( user= request.user, data=request.POST, files=request.FILES)

  if request.method == 'POST':
    form.photographer = request.user
    if form.is_valid():
      photo = form.save(commit=False)
      photo.photographer = request.user
      photo.save()
      return HttpResponseRedirect('/photo/%d/' % photo.id )

您的入站表单处理对我来说似乎有些奇怪,但是我通常不使用ModelForm。 这是我的一般情况:

def some_form_view(request): 
  if request.method != 'POST': 
    raise Http404  # or whatever 
  form_data = FormClass(request.POST, request.FILES)
  if not form_data.is_valid():
    context['form'] = form_data 
    return render_to_response(...)  # invalid for m

  new_object = ModelObject(
      field=form_data.cleaned_data['field'], 
      other_field=form_data.cleaned_data['other_field'])
  new_object.save()

  context['new_object'] = new_object
  return render_to_response(...)  # success 

所以要注意的是:

  • 我认为“ form.reservation”不是有效的标识符。 您应该只说“ print form”或“ print str(form)”,而不要尝试打印各个字段。

  • 几乎可以肯定,在对该数据执行任何操作之前,应先调用is_valid()。 如果表单本身无效,则应该/将引发表单验证错误。

  • 仅曾经直接通过form.cleaned_data ['foo']而不是.data来访问表单数据,因为您正在访问的是来自用户的潜在危险信息。

希望这可以帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM