Django Hidden Foreign Key in form using Meta model
django, foreign-keys, forms, hidden, widget
Solution
Add `exclude = ('original_cookbook',)` to your form's `Meta` class.
Then, in your `if form.is_valid()` code, do something like:
....
recipe = form.save(commit=False)
recipe.original_cookbook = whatever_that_is
recipe.save()
...
Problem
I am working on a cookbook website using django and have run into a problem with a foreign key field in my form the problem is that when i create my recipe i need to have a foreign key pointing to the cookbook that created this recipe but I don't want the user creating the recipe to see the original_cookbook field (they shouldn't have to) I believe I need to use a widget (HiddenInput) but am I getting confused with the examples given on other sites. Also my friend mentioned something about setting an initial value in the original_cookbook view tl;dr: I want to point the fk to the users cookbook while keeping the original_cookbook field hidden. relevant code: form: ``` class RecipeForm(forms.ModelForm): class Meta: model = Recipe ``` model: ``` class Recipe(models.Model): def __unicode__(self): return self.name original_cookbook = models.ForeignKey(Cookbook) #cookbooks = models.ManyToManyField('Cookbook', related_name = 'recipes') name = models.CharField(max_length=200) author = models.CharField(max_length= 100) picture = models.ImageField(upload_to = 'Downloads', blank=True) pub_date = models.DateTimeField('date published', auto_now_add=True, blank=True) ingredients = models.TextField() steps = models.TextField() prep_time = models.IntegerField() TYPE_CHOICES= ( ('SW', 'Sandwich'), ('AP', 'Appetizers'), ('SD', 'Sauces and Dressings'), ('SS', 'Soups and Salads'), ('VG', 'Vegetables'), ('RG', 'Rice, Grains and Beans'), ('PA', 'Pasta'), ('BR', 'Breakfast'), ('MT', 'Meat'), ('SF', 'Seafood'), ('BP', 'Bread and Pizza'), ('DT', 'Desserts'), ) type = models.CharField(max_length = 2, choices=TYPE_CHOICES) def index_queryset(self): return self.objects.all() ``` view: ``` def createrecipe(request): if not request.user.is_authenticated(): return HttpResponseRedirect('/index/') else: if request.method == 'POST': form = RecipeForm(request.POST) if form.is_valid(): recipe = form.save() user = request.user cookbooks = user.cookbooks cookbook = cookbooks.all()[0] cookbook.recipes.add(recipe) return HttpResponseRedirect('/account') else: form = RecipeForm() return render_to_response('cookbook/createrecipe.html', {'form':form}, context_instance=RequestContext(request)) ```