开发者

Django: How to prepopulate file upload path with current file path?

开发者 https://www.devze.com 2023-04-02 16:04 出处:网络
I have a modelform that my views generate an HTML form for editing content. Currently, it\'s able to pull in the current stored text content, like this:

I have a modelform that my views generate an HTML form for editing content. Currently, it's able to pull in the current stored text content, like this:

@login_required
def edit_person(request, s_id, p_id):
    p = get_object_or_404(Person, id=p_id)

    if request.method == 'POST': 
        form = PersonForm(request.POST, request.FILES)
        if form.is_valid():
            p.name = request.POST['name']
            p.title = request.POST['title']
            handle_uploaded_file(request.FILES['photo'], request.FILES['photo'].name, 'media/images/people/')
            p.photo = request.FILES['photo']
            p.order = request.POST['order']  
            p.save()
            return HttpResponseRedirect('/section/'+s_id+'/')
        else:
            return HttpResponse("error")

    else:
        form = PersonForm({ 'name': p.name, 'title': p.title, 'photo': p.photo, 'order': p.order })
        return render_to_response('auth/edit-form.html', { 'form': form }, context_instance=RequestContext(request))

    return HttpResponseRedirect('/section/'+s_id+'/')

However, the photo file path is blank. I don't want the user to have to upload a new file every time they edit something if they don't want to change the image. How do I get 开发者_如何转开发the file upload field to appear pre-populated and not overwrite itself if they don't change it? Thanks.


Believe it or not, it can be done! However, it requires the use of a custom django app called django-file-resubmit

Note that app as given only works for the widgets in admin and requires sorl-thumbnail.

You may prefer to use my fork:

https://github.com/JordanReiter/django-file-resubmit

It's a general-purpose version for use everywhere a ModelForm is used that doesn't have any other prerequisites.

It's pretty cool in that it automagically stores the file on submission (even if there is a validation error) and retrieves it from the cache when the widget is rendered in the form.

This is literally all you have to do to implement it:

import file_resubmit.widgets

class PersonForm:
    """ existing code here """
    photo = forms.ImageField(required=False, widget=file_resubmit.widgets.ResubmitImageWidget())
0

精彩评论

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

关注公众号