1

I'm having trouble saving data for an intermediate field. I have forms (unlisted here) to create Stocks and Portfolios. Now I am trying to build a Membership form to link the two. I followed the django documentation and the code works perfectly in the the API. Then in the views, I can the membership to save fine (I pulled it up in the API afterwards to check), but it doesn't make the make the connection between the Stock and Portfolio. After the membership form, there is a membership object saved in my database but it is not connecting the portfolio to the stock.

Thanks in advance.

Here are my models:

class Stock(models.Model):
    name = models.CharField(max_length=160)
    ticker = models.SlugField(max_length=20)
    created = models.DateTimeField(auto_now_add=True, blank=True)

class Portfolio(models.Model):
    name = models.CharField(max_length=160)
    stocks = models.ManyToManyField(Stock, through='Membership')

class Membership(models.Model):
    stock = models.ForeignKey(Stock)
    portfolio = models.ForeignKey(Portfolio)
    shares = models.IntegerField(default=0)

class StockForm(forms.ModelForm):
    class Meta:
        model = Stock
        exclude = []

class PortfolioForm(forms.ModelForm):
    class Meta:
        model = Portfolio
        exclude = []

class MembershipForm(forms.ModelForm):
    class Meta:
        model = Membership
        exclude = []    

And here are my views.py:

def membership_form(request):
    if request.method == 'POST':
        form = MembershipForm(request.POST, request.FILES)
        if form.is_valid():
            new_obj = form.save(commit=False)
            new_obj.save()
            membership = Membership.objects.create( portfolio=new_obj.portfolio ,stock=new_obj.stock)
            membership.save()
            return HttpResponseRedirect(reverse('portfolios', args=[]))
    else: 
        form = MembershipForm(None)
        return render(request, 'portfolio/form.html', {'form': form})

I based the views off Django m2m form save " through " table .

Community
  • 1
  • 1
aled1027
  • 1,326
  • 2
  • 13
  • 17
  • 1
    Your view code looks quite off. First you init the `MembershipForm` then save the right membership if form is valid, then you save the membership again manually?? Also how did you populate the data for your form? – Hieu Nguyen Jul 21 '13 at 11:47
  • Ok, I removed the lines where I manually remove it, but the data still isn't being saved correctly in the database. I used `form.as_table()` in html. Would that make a difference? – aled1027 Jul 23 '13 at 01:17

1 Answers1

1

Write a custom form and save the relationship inside it.

I have taken the example as classes of of email address associated with an email that i wanted to send

class SendForm (forms.ModelForm) :

    To = forms.ModelMultipleChoiceField(
        queryset=EmailId.objects.filter(),required=False,widget=FilteredSelectMultiple(('To'), False))

    def __init__(self, *args, **kwargs):
        initial = kwargs.setdefault('initial', {})
        if 'instance' in kwargs:
            initial['To']=kwargs['instance'].To.all()
        super(SendForm, self).__init__(*args, **kwargs)

    def save(self, commit=True):
        instance = forms.ModelForm.save(self, commit)
        instance.save(send=0)
        es = [e for es in self.cleaned_data['To']]

        for relation in instance.To.all():
            instance.To.remove(relation)
        for e in es:
            instance.To.add(e)

        instance.save(send=1)

        return instance
    class Meta:
        model =SentEmail
sj7
  • 1,291
  • 1
  • 12
  • 26