When editing an object in django the ImageField is not populated

那年仲夏 提交于 2020-02-27 12:03:22

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/2039749/when-editing-an-object-in-django-the-imagefield-is-not-populated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!