我正在尝试为现有应用添加新功能,让用户可以创建个人资料并上传他们宠物的照片。
当用户登录时,他会被重定向到显示其姓名的个人资料中,并且他还可以将自己的照片添加到模型中,该模型将显示在个人资料页面上。
目前,我可以将名称检索到模板中,但我似乎无法同时显示用户名和上传图片。
每当我点击添加图片时,它都不会让用户上传图片而是我收到此错误
'PictureForm' object has no attribute 'save'
pet = form.save(commit =False) ...
我可以设计页面让用户上传图片,但不能同时显示名称。
我认为问题出现在我的profile.html和views函数的views.py
中我的views.py部分
@login_required
def Profile(request):
Person = request.user.get_profile()
if not request.user.is_authenticated():
return HttpResponseRedirect('/login/')
if request.method == "POST":
form = PictureForm(request.POST ,request.FILE or None)
if form.is_valid():
pet = form.save(commit =False)
pet.save()
context = (
{'Person': Person} ,
{'form':PictureForm()}
)
return render_to_response('profile.html', context, context_instance=RequestContext(request))
我的forms.py部分
from django import forms
from django.contrib.auth.models import User
from django.forms import ModelForm
from pet.models import *
class PictureForm(forms.Form):
class Meta:
model = Person
fields = ('image')
我的个人资料
{% if Person %}
<ul>
<li>Name : {{Person.name}} </li>
</ul>
{% endif %}
<form method="POST" enctype="multipart/form-data" "action" >
{% csrf_token %}
<ul>
{{ form.as_ul }}
</ul>
<input type = "submit" value= "Add Picture" />
</form>
我的models.py
from django.db import models
from django.db.models.signals import post_save
from django.contrib.auth.models import User
class Person(models.Model):
user = models.OneToOneField(User)
name = models.CharField(max_length=100)
image = models.FileField(upload_to="images/",blank=True,null=True)
def __unicode__(self):
return self.name
class Pet(models.Model):
Person = models.ForeignKey(Person)
description = models.CharField(max_length=100)
image = models.FileField(upload_to="images/",blank=True,null=True)
def __unicode__(self):
return self.description
答案 0 :(得分:3)
PictureForm
需要继承forms.ModelForm
,而不是forms.Form
。
答案 1 :(得分:2)
你有一个错字。它应该是request.FILES
。
答案 2 :(得分:1)
删除form.save(commit = False)。只有在覆盖保存方法
时才会这样做@login_required
def Profile(request):
Person = request.user.get_profile()
if not request.user.is_authenticated():
return HttpResponseRedirect('/login/')
if request.method == "POST":
form = PictureForm(request.POST ,request.FILES)
if form.is_valid():
form.save()
context = (
{'Person': Person} ,
{'form':PictureForm()}
)
return render_to_response('profile.html', context, context_instance=RequestContext(request))
更新:
[.....]
board = Board.objects.get(board=picture.board)//remove this
the_id = board.id //remove this
return HttpResponseRedirect(reverse('world:Boat', kwargs={'animal_id': picture.board.id })) // change the_id into picture.board.id
答案 3 :(得分:0)
只需将此功能添加到您的模型
def save(self,*args, **kw):
super(PictureForm,self).save(*args, **kw)