我无法使用django crispy表单正确上传图片字段。表单和页面上的其他所有内容都可以正常工作,但图像字段不会出错或保存,它只是直接通过它。我能够通过管理员添加图片就好了,它只能在我的脆形式上失败。
#views.py
@login_required
def dashboard(request, **kwargs):
'''
perform managerial and administrative tasks for a blog. Only
available to the blog owner
'''
alert_message = ""
status = ""
blog_slug = kwargs['blog']
blog = get_object_or_404(PersonalBlog, slug=blog_slug)
# handle the form submit to update blog data
form = BlogEditForm(instance=blog)
if request.method == "POST":
if blog.owner == request.user:
form = BlogEditForm(request.POST, instance=blog)
if form.is_valid():
form.save()
alert_message = "Your blog data has been updated successfully"
status = "saved"
else:
alert_message = "There was a problem saving the data you entered. Please correct the errors above."
status = "error"
else:
alert_message = "You do not have access to update this blog's information."
status = "error"
return render(request, "blogcontent/dashboard.html", {'alert_message':alert_message,
'status':status, 'form':form})
#forms.py
class BlogEditForm(ModelForm):
description = forms.CharField(widget = forms.Textarea())
twitter = forms.CharField(required=False, help_text="show twitter feed, and allow people to interact with you on twitter")
twitter_widget_id = forms.CharField(required=False, help_text="required to show a timeline widget for your twitter account. " + \
"<span class='glyphicon glyphicon-question-sign'></span>")
instagram = forms.CharField(required=False, help_text="show instagram feed on your blog page")
disqus = forms.CharField(required=False, help_text="allow comments at the bottom of your blog posts")
class Meta:
model = PersonalBlog
def __init__(self, *args, **kwargs):
super(BlogEditForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.layout = Layout(
Fieldset(
'<h2 class="text-center">Edit data about your blog</h2>',
Field('owner', type="hidden"),
Field('title', type="hidden"),
Div('description', css_class="col-md-12"),
Div('twitter', css_class="col-md-6"),
Div('twitter_widget_id', css_class="col-md-6"),
Div('instagram', css_class="col-md-6"),
Div('disqus', css_class="col-md-6"),
Div('logo', css_class="col-md-12"),
),
ButtonHolder(
Submit('submit', 'Update Info', css_class='btn-lg'),
css_class="text-center"
),
)
#dashboard.html
<form method="post" enctype="multipart/form-data">
{% crispy form %}
</form>
答案 0 :(得分:3)
form = BlogEditForm(request.POST, request.FILES, instance=blog)
答案 1 :(得分:2)
您是否尝试过更改:
<form method="post" enctype="multipart/form-data">
{% crispy form %}
</form>
只是:
{% load crispy_forms_tags %}
{% crispy form %}
同样在您的代码中,您正在致电:
if form.is_valid():
form.save()
您不希望save()
表单。您希望将表单数据保存到模型实例。所以create()
使用表单数据的模型。这也可能是原因。 Forms
仅用于保存数据,直到您清理数据并使用model
将其保存到数据库。