title: Initially populate FileField in Django-Form
body: <p>I have a model that describes a Webpage. The <code>source_upload</code> field represents a screenshot of the webpage. </p>
  
  <p>For adding site-objects to my application, I use a django class-based <code>CreateView</code>. This works really well. </p>
  
  <p>Now I'm trying to add a semi-automatic way of adding sites. You can pass an URL to the view and the view fills the form automatically (and makes a screenshot of the webpage). The user should be able to review all the auto-extracted fields - especially the auto generated screenshot image - change them and hit the save button to add the object to the database and the image (if approved) to its final location.</p>
  
  <p>I tried to implement this in the <code>get_initial</code> method of the view. This works quite well except for the screenshot-<code>FileField</code>. The path I set in <code>initial['source_upload']</code> is not shown in the <code>current: &lt;link&gt;</code>part of the FileInput widget of the form.</p>
  
  <p><strong>How can I give the filefield an initial value?</strong></p>
  
  <hr>
  
  <p><strong>models.py</strong></p>
  
  <pre><code>class Site(models.Model):
  
      def get_source_upload_path(instance, filename):
          now = datetime.datetime.now()
          return "appname/sites/{}/{}/{}/site_{}_{}".format(now.year, now.month, now.day, instance.pk, filename)
  
      creationDate = models.DateTimeField(auto_now_add=True)
      last_modifiedDate = models.DateTimeField(auto_now=True)
      creator = models.ForeignKey('auth.User', related_name='siteCreated')
      last_modifier = models.ForeignKey('auth.User', related_name='siteLast_modified')
  
      date = models.DateTimeField(default=datetime.date.today)    
      title = models.CharField(max_length=240, blank=True)
      body = models.TextField(max_length=3000)
  
      source_url = models.URLField(blank=True)
      source_upload = models.FileField(upload_to=get_source_upload_path, blank=True)
  
      keywords = models.ManyToManyField("Keyword")
  </code></pre>
  
  <p><strong>urls.py</strong></p>
  
  <pre><code>url(r'site/add/$', views.SiteCreate.as_view(), name='site-add'),
  url(r'site/add/(?P&lt;source_url&gt;[A-Za-z0-9\-._~:/\[\]@!$&amp;\'\(\)\*\+,;=?#]+)/$', views.SiteCreate.as_view(), name='site-add-fromurl'),
  </code></pre>
  
  <p><strong>forms.py</strong></p>
  
  <pre><code>class SiteForm(ModelForm):
      class Meta:
          model = Site
          fields = ['date', 'title', 'body', 'source_url', 'source_upload', 'keywords']
          widgets = {
              'keywords' : CheckboxSelectMultiple(),
          }
  </code></pre>
  
  <p><strong>views.py</strong></p>
  
  <pre><code>class SiteCreate(LoginRequiredMixin, CreateView):
      model = Site
      template_name = 'appname/site_form.html'
      form_class = SiteForm
      success_url = reverse_lazy('appname:index')
  
      def form_valid(self, form):
          form.instance.creator = self.request.user
          form.instance.last_modifier = self.request.user
          return super(SiteCreate, self).form_valid(form)
  
      def get_initial(self):
          # Get the initial dictionary from the superclass method
          initial = super(SiteCreate, self).get_initial()
  
          try:
              #get target url from request
              fullpath = self.request.get_full_path()
              fullpath = fullpath.split("/")
              fullpath, querystring = fullpath[3:-1], fullpath[-1]
              source_domain = fullpath[2]
              fullpath = "/".join(fullpath)
              fullpath += querystring
  
              source_url = fullpath
  
              if (not source_url.startswith("http://") and not source_url.startswith("https://")):
                  print("ERROR: url does not start with http:// or https://")
                  return initial
  
              # ...
              # extract title, date &amp; others with BeautifulSoup
              # ...
  
              #extract screenshot  (is there a better way?)
              from selenium import webdriver
              driver = webdriver.Firefox()
              driver.get(source_url)
              tmpfilename = "{}_{}.png".format(get_valid_filename(source_domain), get_valid_filename(title[:30]))
              now = datetime.datetime.now()
              tmpfilepath_rel =  "appname/sites/tmp/{}/{}/{}/{}".format(now.year, now.month, now.day, tmpfilename)
              tmpfilepath = settings.MEDIA_ROOT + tmpfilepath_rel
  
              folder=os.path.dirname(tmpfilepath)
              if not os.path.exists(folder):
                  os.makedirs(folder)
              driver.save_screenshot(tmpfilepath)
              driver.quit()
  
              initial = initial.copy()
              initial['source_url'] = source_url
              initial['title'] = title
              initial['date'] = soup_date
              initial['body'] = body
              initial['source_upload'] = tmpfilepath_rel
          except KeyError as e:
              print("no valid source_url found. zeige also ganz normales add/new template")
          except IndexError as e:
              print("no valid source_url found. zeige also ganz normales add/new template")
  
          return initial
  </code></pre>
  
  <p><strong>site_form.html</strong> (Used for Create and Update view)</p>
  
  <pre><code>{% extends "appname/base.html" %}
  {% load staticfiles %}
  {% block header %}
      &lt;link rel="stylesheet" type="text/css" href="{% static 'appname/model_forms.css' %}" /&gt;
  {% endblock %}
  {% block body %}
          &lt;form enctype="multipart/form-data" action="" method="post"&gt;{% csrf_token %}
  
              &lt;div class="fieldWrapper"&gt;
                  &lt;div class="error"&gt;{{ form.date.errors }}&lt;/div&gt;
                  &lt;div class="label"&gt;{{ form.date.label_tag }}&lt;/div&gt;
                  &lt;div class="field"&gt;{{ form.date }}&lt;br /&gt;{{ form.date.help_text }}&lt;/div&gt;
                  &lt;div class="floatclear"&gt;&lt;/div&gt;
              &lt;/div&gt;
              &lt;div class="fieldWrapper"&gt;
                  &lt;div class="error"&gt;{{ form.title.errors }}&lt;/div&gt;
                  &lt;div class="label"&gt;{{ form.title.label_tag }}&lt;/div&gt;
                  &lt;div class="field"&gt;{{ form.title }}&lt;br /&gt;{{ form.title.help_text }}&lt;/div&gt;
                  &lt;div class="floatclear"&gt;&lt;/div&gt;
              &lt;/div&gt;
              &lt;div class="fieldWrapper"&gt;
                  &lt;div class="error"&gt;{{ form.body.errors }}&lt;/div&gt;
                  &lt;div class="label"&gt;{{ form.body.label_tag }}&lt;/div&gt;
                  &lt;div class="field"&gt;{{ form.body }}&lt;br /&gt;{{ form.body.help_text }}&lt;/div&gt;
                  &lt;div class="floatclear"&gt;&lt;/div&gt;
              &lt;/div&gt;
              &lt;div class="fieldWrapper"&gt;
                  &lt;div class="error"&gt;{{ form.source_url.errors }}&lt;/div&gt;
                  &lt;div class="label"&gt;{{ form.source_url.label_tag }}&lt;/div&gt;
                  &lt;div class="field"&gt;{{ form.source_url }}&lt;br /&gt;{{ form.source_url.help_text }}&lt;/div&gt;
                  &lt;div class="floatclear"&gt;&lt;/div&gt;
              &lt;/div&gt;
              &lt;div class="fieldWrapper"&gt;
                  &lt;div class="error"&gt;{{ form.source_upload.errors }}&lt;/div&gt;
                  &lt;div class="label"&gt;{{ form.source_upload.label_tag }}&lt;/div&gt;
                  &lt;div class="field"&gt;{{ form.source_upload }}&lt;br /&gt;{{ form.source_upload.help_text }}&lt;/div&gt;
                  &lt;div class="floatclear"&gt;&lt;/div&gt;
              &lt;/div&gt;
              &lt;div class="fieldWrapper"&gt;
                  &lt;div class="error"&gt;{{ form.keywords.errors }}&lt;/div&gt;
                  &lt;div class="label"&gt;{{ form.keywords.label_tag }}&lt;/div&gt;
  
                  &lt;div class="field"&gt;
                      &lt;ul class="checkbox-grid"&gt;
                          {% for kw in form.keywords %}
                              &lt;li&gt;
                                  {{ kw.tag }}
                                  &lt;label for="{{ kw.id_for_label }}"&gt;
                                      {{ kw.choice_label }}
                                  &lt;/label&gt;
                              &lt;/li&gt;
                          {% endfor %}
                      &lt;/ul&gt;
                      &lt;div class="checkbox_help_text"&gt;&lt;br /&gt;{{ form.keywords.help_text }}&lt;/div&gt;
                  &lt;/div&gt;
                  &lt;div class="floatclear"&gt;&lt;/div&gt;
              &lt;/div&gt;
              &lt;input type="submit" value="Save" /&gt;
          &lt;/form&gt;
          &lt;div id="ObjectHistory"&gt;
              {% if site.pk %}
                  &lt;p&gt;Created by: {{ site.creator }}&lt;/p&gt;
                  &lt;p&gt;Created on: {{ site.creationDate }}&lt;/p&gt;
                  &lt;p&gt;Last modified by: {{ site.last_modifier }}&lt;/p&gt;
                  &lt;p&gt;Last modified on: {{ site.last_modifiedDate }}&lt;/p&gt;
                  &lt;p&gt;Now: {% now "Y-m-d H:i:s" %} &lt;a href="{% url 'appname:site-delete' site.pk %}"&gt;&lt;button&gt;delete&lt;/button&gt;&lt;/a&gt;&lt;/p&gt;
              {% else %}
                  &lt;p&gt;This is a new Site!&lt;/p&gt;
                  &lt;p&gt;Now: {% now "Y-m-d H:i:s" %}&lt;/p&gt;
              {% endif %}
          &lt;/div&gt;
  {% endblock %}
  </code></pre>