嗨,我是django的新手,我在django cms中创建了自定义插件,这是其他字段容易保存的形式,但是image字段却没有保存。
这是我的代码,如果我遗漏了一些我真的卡在这里的代码,请告诉我,您的帮助将不胜感激。
class Blogs(models.Model):
name = models.CharField(u'Name',
blank=True,
default='',
help_text=u'Your name',
max_length=64,
)
description = models.TextField(u'Description',
blank=True,
default='',
help_text=u'Enter your Blog.',
)
comments = models.TextField(u'Short Description',
blank=True,
default='',
help_text=u'Short title of the Blog.',
)
images = models.ImageField(
upload_to='blog_image',
default='blog_image/black.png',
blank=True
)
# Meta, non-form data
contact_date = models.DateTimeField(
u'contact date',
blank=True,
default=timezone.now,
help_text=u'When this person completed the contact form.',
)
was_contacted = models.BooleanField(u'has been contacted?',
default=False,
help_text=u'Check this if someone has already reached out to this person.',
)
notes = models.TextField(u'contact notes',
blank=True,
default='',
help_text=u'Internal notes relating to contacting this person.',
)
referer = models.CharField(u'referring page',
blank=True,
default='',
help_text=u'This is the page the visitor was on before coming to the contact page.',
max_length=2048,
)
def send_notification_email(self):
subject.txt', {
'contact': self,
})
email_body = render_to_string('contacts/notification-body.txt', {
'contact': self,
})
try:
send_mail(
email_subject,
email_body,
settings.SERVER_EMAIL,
settings.MANAGERS,
fail_silently=(not settings.DEBUG)
)
except Exception:
if (settings.DEBUG):
raise
def save(self, *args, **kwargs):
if not self.pk:
try:
self.send_notification_email()
except:
pass
super(Blogs, self).save(*args, **kwargs)
def __unicode__(self):
return '%s (%s)' % (self.name, str(self.contact_date),)
class BlogPluginModel(CMSPlugin):
title = models.CharField(u'title',
blank=True,
help_text=u'Optional. Title of the widget.',
max_length=64,
)
def __unicode__(self):
return self.title
class BlogPlugin(CMSPluginBase):
model = BlogPluginModel
name = _("Blog Form")
render_template = "blogs/_blogs_widget.html"
def render(self, context, instance, placeholder):
try:
path = context['request'].path
except:
path = ''
form = BlogAjaxForm(initial={'referer': path})
context.update({
"title": instance.title,
"form": form,
"form_action": reverse("blogging_form"),
})
return context
plugin_pool.register_plugin(BlogPlugin)
class BlogBaseForm(ModelForm):
class Meta:
abstract = True
required_css_class = 'required'
verify_email = forms.EmailField(
label=u'Verify email',
help_text=u'Please retype your email address here.',
max_length=255,
required=True,
)
required_fields = []
class blogForm(BlogBaseForm):
images=forms.ImageField(help_text="Upload image: ", required=False)
class Meta:
model = Blogs
fields = [
'name','images', 'description', 'comments', 'referer',
]
widgets = {
'referer': forms.HiddenInput(),
}
required_fields = ['name', 'email', 'verify_email', ]
class BlogAjaxForm(BlogBaseForm):
images=forms.ImageField(help_text="Upload image: ", required=False)
class Meta:
model = Blogs
fields = ['name','images', 'description','comments','referer', ]
widgets = { 'referer': forms.HiddenInput(),}
class BlogFormView(FormView):
form_class = BlogBaseForm
template_name = 'contacts/contact_form.html'
def get_initial(self):
"""
still preserve this original HTTP_REFERER.
"""
initial = super(BlogFormView, self).get_initial()
initial['referer'] = self.request.META.get('HTTP_REFERER', ''),
return initial
def get_success_url(self):
page = get_object_or_404(
Page,
reverse_id='blog_form_submission',
publisher_is_draft=False
)
return page.get_absolute_url()
def form_valid(self, form):
self.object = form.save()
return super(BlogFormView, self).form_valid(form)
class AjaxableResponseMixin(object):
def __init__(self):
self.request = None
self.object = Blogs
def render_to_json_response(self, context, **response_kwargs):
data = json.dumps(context)
response_kwargs['content_type'] = 'application/json'
return HttpResponse(data, **response_kwargs)
def form_invalid(self, form):
response = super(AjaxableResponseMixin, self).form_invalid(form)
if self.request.is_ajax():
return self.render_to_json_response(form.errors) # , status=400)
else:
return response
def form_valid(self, form):
response = super(AjaxableResponseMixin, self).form_valid(form)
if self.request.is_ajax():
data = {
'pk': self.object.pk,
}
return self.render_to_json_response(data)
else:
return response
class BlogFormAjaxView(AjaxableResponseMixin, FormView):
form_class = BlogAjaxForm
http_method_names = [u'post']
template_name = 'contacts/_contact_widget.html'
form = BlogAjaxForm(http_method_names)
def get_success_url(self):
page = get_object_or_404(
Page,
reverse_id='blog_form_submission',
publisher_is_draft=False
)
return page.get_absolute_url()
def form_valid(self, form):
self.object = form.save(commit=True)
return super(BlogFormAjaxView, self).form_valid(form)
urlpatterns = [
url(
r'^blogging_form/$',
BlogFormAjaxView.as_view(),
name='blogging_form'
),
url(r'^$', BlogFormView.as_view(), name='Blog_Form'),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
{% load i18n static sekizai_tags %}
{% addtoblock "js" %}<script src="{% static 'blogs/scripts/Blogs.js' %}"></script>
{% endaddtoblock %}
{% addtoblock "css" %}
<link rel="stylesheet" href="{% static 'contacts/css/styles.css' %}">
{% endaddtoblock %}
{% addtoblock "js" %}
<script src="{% static 'http://malsup.github.com/jquery.form.js' %}"></script>
{% endaddtoblock %}
<div class="Blogs-plugin plugin">
<div class="inner">
<div class="Blog-form">
{% if title %}<h3>{{ title }}</h3>{% endif %}
<form method="post" action="{{ form_action }}" enctype="multipart/form-data">
{% csrf_token %}
{% for hidden in form.hidden_fields %}
{% if hidden.name == 'referer' %}
<input type="hidden" name="{{ hidden.name }}" value="{{ hidden.value }}">
{% endif %}
{% endfor %}
{% for visible in form.visible_fields %}
<div class="field-wrapper field-row half {{ visible.css_classes }}">
{{ visible.label_tag }}
<div class="help-text">{{ visible.help_text }}</div>
<div class="error empty"></div>
{{ visible }}
</div>
{% endfor %}
<input type="submit" value="Submit">
</form>
<div class="legend"><span class="required">*</span> Required field
</div>
<div class="success" style="display:none">Thank you, a member of our
team will contact you shortly, if appropriate.
</div>
<div class="errors" style="display:none"><span class="form-errors">
</span>
</div>
</div>
</div>
</div>
(function($){
"use strict";
$(function(){
$('.Blogs-plugin input[type=submit]').on('click',
function(evt){
var $form = $(this).parents('form').eq(0);
function handleResponse(data){
if (data.pk) { // Success!
$form.siblings('.success').html(data.success).show(100);
$form.add('.legend').hide(100);
}
else { // Validation Issues...
//
// data will a dictionary like so:
// { 'field_name': ['error1', 'error2'], ... }
//
$form.find('.error').empty();
$.each(data, function(key, value){
var $field = $form.find('input[name='+key+']').first();
$field.parents('.fieldwrapper').find('.error').html(value.join(' '));
});
if (data.__all__) {
$form.siblings('.errors').find('.form-
errors').html(data.__all__.join(' '));
}
else {
$form.siblings('.errors').find('.form-errors').empty();
}
$form.siblings('.errors').show(100);
}
}
evt.preventDefault();
$form.siblings('.errors, .success').hide(100);
$.ajax({
type: 'POST',
url: $form.attr('action'),
data: $form.serialize(),
}).always(handleResponse);
});
});
}(window.jQuery));