Search code examples
djangoformsmodels

Django Form instance not working


I'm trying to have a user profile page where users can manager the "customers" they are subscribed to. For testing purposes i'm calling the whole form {{ customer_subscription }} in the template, and it is returning the right instance of the user, but i'm expecting it to also have that user's subscribed "customers" highlighted on the form instance but it's not selecting anything. What am I doing wrong?

models.py

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    phone = models.CharField(max_length=10, blank=True)

    def __unicode__(self):
        return self.user.username

class Customers(models.Model):
    customer = models.CharField(max_length=200)

    def __unicode__(self):
        return self.customer

class Customer_Subscription(models.Model):
    user = models.ForeignKey(User)
    customers = models.ManyToManyField('Customers')
    def __unicode__(self):
        return (self.user)

forms.py

class CustomerSubscriptionForm(forms.ModelForm):
    class Meta:
        model = Customer_Subscription
        fields = '__all__'

views.py

def profile(request):

    userprofile = UserProfile.objects.get(user=request.user)
    customer_subscription = CustomerSubscriptionForm(instance=userprofile)
    return render_to_response('profile.html', {'userprofile' : userprofile, 'customer_subscription':customer_subscription, },context_instance=RequestContext(request))

Solution

  • When you create the ModelForm, have to use a CustomerSubscription object instance instead of a UserProfile

    def profile(request):
        userprofile = UserProfile.objects.get(user=request.user)
        customer_subs = CustomerSubscription.objects.get(user=userprofile)
        customer_subscription = CustomerSubscriptionForm(instance=customer_subs)
        return render_to_response('profile.html', {'customer_subscription' : customer_subscription, 'customer_subscription':customer_subscription, },context_instance=RequestContext(request))