Note that there are some explanatory texts on larger screens.

plurals
  1. PODjango problems with saving a m2m relationship
    text
    copied!<p>I have been able to save m2m relationships with forms in the past, but I am currently have problems with the following and I can't understand why:</p> <pre><code># models.py class File(models.Model): client = models.ManyToManyField(Client) product = models.ForeignKey(Product, related_name='item_product') created = models.DateTimeField(default=datetime.now) created_by = models.ForeignKey(User) # forms.py class FileForm(ModelForm): class Meta: model = File exclude = ('client') def CustomSave(self,product,client,user): temp = self.save(commit=False) temp.product = product temp.client = client # &lt; ?!?! temp.created_by = user temp.save() temp.save_m2m() return temp # views.py def new_client_view(request): if request.method == 'POST': try: i_product = int(request.POST['product']) except ValueError: raise Http404() # get a 'product' from the POST data p = Product.objects.get(id=i_product) formFile = FileForm(p, request.POST, auto_id='f_%s') formItemData = ItemDataForm(p, request.POST, auto_id='i_%s') if formFile.is_valid() and formItemData.is_valid(): c = Client() c.save() tempFile = formFile.CustomSave(p,c,request.user) tempItem = ItemForm().CustomSave(tempFile,request.user) formItemData.CustomSave(tempItem,request.user) return redirect(client_view, c.id) else: return render_to_response('newClient.html', {'error':'The form was not valid'}, context_instance=RequestContext(request)) else: return render_to_response('newClient.html', {}, context_instance=RequestContext(request)) </code></pre> <p>When I try the above I get:</p> <pre><code>'File' instance needs to have a primary key value before a many-to-many relationship can be used. </code></pre> <p>And django indicates the error comes from <code>temp.client = client</code></p> <p>I have tried various permutations of the <code>CustomSave</code> without much success :(</p> <p>Any ideas?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload