Django:AttributeError - 对象没有属性

发布于 2024-10-13 05:31:18 字数 4875 浏览 4 评论 0原文

该视图抛出 AttributeError 说:“PhotoForm”对象没有属性“reservation”。发生了什么 - 函数通过了,但实际上并未上传图像。在调试过程中,表单无效。

我尝试打印

  • form.reservation
  • form.message
  • form.photo

但这显示了此回溯(这就是表单无效且未完成的原因 的基础上构建这个函数

有点困惑,谢谢您的帮助!

运行的函数

<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'

This view is throwing the AttributeError saying :'PhotoForm' object has no attribute 'reservation'. What happens- the function passes, but doesn't actually upload the image. In debugging it, the form is not valid.

I tried printing

  • form.reservation
  • form.message
  • form.photo

But that shows this traceback ( which is the reason why the form isn't valid & not completing the function.

As I built this off other functions that are working, I'm a bit confused. Thanks for the help!

The HTML Form

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

The View

@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))

The Form:

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

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

The Model:

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/")

The traceback

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'

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

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

发布评论

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

评论(3

找个人就嫁了吧 2024-10-20 05:31:18

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

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

should not forms (with image or file fields) be initialized with request.FILES?

form = PhotoForm(request.POST, request.FILES)
始终不够 2024-10-20 05:31:18

关键是在表单中包含 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 )

The key was having files=request.FILES in the form.

@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 )
仙气飘飘 2024-10-20 05:31:18

您的入站表单处理对我来说有点奇怪,但我通常不使用 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,因为您正在访问来自用户的潜在危险内容。

希望这有帮助。

Your inbound form processing looks a bit odd to me, but I usually don't use ModelForm. Here's what mine generally look like:

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 

So things to note:

  • I don't think "form.reservation" is a valid identifier. You should just say "print form" or "print str(form)" and not try to print the individual fields.

  • You should almost certainly be calling is_valid() before doing anything with that data. That should/will raise the form validation errors if the form itself is invalid.

  • Only ever access the form data directly through form.cleaned_data['foo'] and never via .data, because you're accessing something potentially dangerous coming in from the user.

Hope this helps.

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