开发者

When editing an object in django the ImageField is not populated

I'm trying to edit an existing object through a form. Every thing is working fine except for the ImageField not being populated with the current value.

Here's the model:

class Post(models.Model):
    author = models.ForeignKey(User, editable=False)
    slug = models.SlugField(max_length = 110, editable=False)
    title = models.CharField(verbose_name='Blog Title', max_length=40, blank=False)
    body = models.TextField(verbose_name='Body')
    thumbnail = models.ImageField(upload_to = 'posts/%Y/%m')

Here's the view

@login_required
def edit_profile(request, form_class=UserProfileForm, success_url=None, template_name='profiles/edit_profile.html', extra_context=None):

try:
    profile_obj = request.user.get_profile()
except ObjectDoesNotExist:
    return HttpResponseRedirect(reverse('profiles_create_profile'))

if success_url is None:
    success_url = reverse('profiles_profile_detail',
                          kwargs={ 'username': request.user.username })
if form_class is None:
    form_class = utils.get_profile_form()
if request.method == 'POST':
    form = form_class(data=request.POST, files=request.FILES, instance=profile_obj)
    if form.is_valid():
        form.save()
        return HttpResponseRedirect(success_url)
else:
    form = form_class(instance=profile_obj)

if extra_context is N开发者_运维百科one:
    extra_context = {}
context = RequestContext(request)
for key, value in extra_context.items():
    context[key] = callable(value) and value() or value

return render_to_response(template_name,
                          { 'form': form,
                            'profile': profile_obj, },
                          context_instance=context)

This object did have a thumbnail attached but when I went to edit, nothing showed up in the Thumbnail field


I believe the answer lies in the fact that the file input field, when it displays a value, displays the local path to the file on the user's computer that was selected. This value is not saved in Django anywhere so Django can't and won't display this value in the form when editing.

What you need to do is print each field individually in the template instead of printing the form as a whole. Then, with your thumbnail field, show the currently selected thumbnail as an actual image on the page and use the file input field to allow the user to upload a new image.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜