title: Set field foreign key value directly in the view Django
body: <p>I have a model named record but it requires a foreign key (barcode)  and I don't want to add it in the form with a select (the way that django does it by default) instead of that I want to insert it manually , so I did this in the <strong>forms.py</strong></p>
  
  <pre><code>class add_record_form(forms.ModelForm):
      barcode = forms.CharField()
      class Meta:
          model = Record
          exclude = ('product',)
  </code></pre>
  
  <p>But I don't know how to pass the value to my view and add it to the record table. I get the error "Record.barcode has to be an instance of barcode" </p>
  
  <p>And when I got the barcode instance then I had to add the product associated to that barcode in the view , that's why I have excluded the product field in the form.</p>
  
  <p><strong>views.py</strong></p>
  
  <pre><code>def add_barcode_view(request):
  
      if request.method == 'POST':
          formu = add_record_form(request.POST)
          if formu.is_valid():
              bcode = formu.cleaned_data['barcode']
              prod = Producto.objects.get(barcode=bcode)
              cant = formu.cleaned_data['amount']
              aux =  prod.amount - cant
              add = formu.save(commit = False)
              if (aux &gt;= 0):
                  prod.amount= aux
                  prod.save()
                  add.save()
                  return HttpResponseRedirect('/record/%s' %add.id)
              else:
                  formu = add_record_form(instance = add)
                  mensaje = "amount not available"
                  ctx = {'men':mensaje, 'form': formu}
                  return render_to_response('inventario/add_record.html', ctx, context_instance = RequestContext(request))
  
      else:
          formu = add_record_form()
          ctx = {'form': formu}
          return render_to_response('inventario/add_record.html', ctx , context_instance = RequestContext(request))
  </code></pre>
  
  <p><strong>Record Model and Barcode</strong> 
  I want to insert the code of a barcode manually in the add record form </p>
  
  <pre><code>class Barcode(models.Model):
      code            = models.CharField(max_length=13, unique = True)
      date            = models.DateField(auto_now = True)
  
      def __unicode__(self):
          return self.code
  
  class Record(models.Model):
      barcode         = models.ForeignKey(Barcode)
      record_date     = models.DateField(auto_now = True)
      producto        = models.ForeignKey(Producto)
      amount          = models.IntegerField()
      description     = models.TextField(max_length=150)
  </code></pre>
  
  <p><strong>Traceback</strong> </p>
  
  <pre><code>Environment:
  
  
  Request Method: POST
  Request URL: http://localhost:8000/add/record/
  
  Django Version: 1.5.3
  Python Version: 2.7.9
  Installed Applications:
  ('django.contrib.auth',
   'django.contrib.contenttypes',
   'django.contrib.sessions',
   'django.contrib.sites',
   'django.contrib.messages',
   'django.contrib.staticfiles',
   'django.contrib.admin',
   'django.contrib.admindocs',
   'sif.apps.home',
   'sif.apps.inventario',
   'sif.apps.web_services.ws_producto',
   'rest_framework')
  Installed Middleware:
  ('django.middleware.common.CommonMiddleware',
   'django.contrib.sessions.middleware.SessionMiddleware',
   'django.middleware.csrf.CsrfViewMiddleware',
   'django.contrib.auth.middleware.AuthenticationMiddleware',
   'django.contrib.messages.middleware.MessageMiddleware')
  
  
  Traceback:
  File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
    115.                         response = callback(request, *callback_args, **callback_kwargs)
  File "D:\MIS DOCUMENTOS\Documents\GitHub\proyecto_formativo\sif\sif\apps\inventario\views.py" in add_record_view
    156.      if formu.is_valid():
  File "C:\Python27\lib\site-packages\django\forms\forms.py" in is_valid
    126.         return self.is_bound and not bool(self.errors)
  File "C:\Python27\lib\site-packages\django\forms\forms.py" in _get_errors
    117.             self.full_clean()
  File "C:\Python27\lib\site-packages\django\forms\forms.py" in full_clean
    274.         self._post_clean()
  File "C:\Python27\lib\site-packages\django\forms\models.py" in _post_clean
    315.         self.instance = construct_instance(self, self.instance, opts.fields, opts.exclude)
  File "C:\Python27\lib\site-packages\django\forms\models.py" in construct_instance
    52.             f.save_form_data(instance, cleaned_data[f.name])
  File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py" in save_form_data
    466.         setattr(instance, self.name, data)
  File "C:\Python27\lib\site-packages\django\db\models\fields\related.py" in __set__
    405.                                  self.field.name, self.field.rel.to._meta.object_name))
  
  Exception Type: ValueError at /add/record/
  Exception Value: Cannot assign "u'144253491444'": "Record.barcode" must be a "Barcode" instance.
  </code></pre>