David542
David542

Reputation: 110093

Trouble getting object in Django's models

I have a user submission form, and the user supplies his name and email. Each email is associated to a network (by an admin, prior to user registration), and based upon a user's email he will be assigned to that network.

Here is what the models.py looks like --

class Network(models.Model):
    network = models.CharField(max_length=50)
    location = models.CharField(max_length=50)

class EmailList(models.Model):
    email = models.EmailField(blank=True)
    network = models.CharField(max_length=50)

class User(models.Model):
    name = models.CharField(max_length=50)
    email = models.EmailField(max_length=50)
    network = models.ForeignKey(Network)       

And in the views.py this is what I am using to try and insert the record into the database --

User.objects.create(
name = cd['name']
email=cd['email'],
network= EmailList.objects.filter(email=request.POST.get('email'))['network'])

However, I am getting an exception TypeError from the network= line. What should the syntax be here to 'pull' and insert the network associated with the email into the database? What am I doing incorrectly

Update

Here is the code I used in views.py to get it working.

email_list = EmailList.objects.get(email=cd['email'])
network= Network.objects.get(network=email_list.network)
User.objects.create(
    name=cd['name'], 
    email=cd['email'], 
    network=network)

When I tried setting the variable email = cd['email'] and then defining the email_list using that variable like so -- email_list = EmailList.objects.get(email=email), it would raise an exception saying Queryset not found in EmailList and would pass a unicode string.

Why does defining the variable before passing it in this case create a unicode string, whereas passing the expression directly in does not?

Upvotes: 0

Views: 144

Answers (1)

dting
dting

Reputation: 39287

Once again, you shouldn't be using the post data directly.

Filter returns a queryset not an instance. That looks like what is causing your problem. Also you need to get a network instance instead of a string to set to User.network:

if email for EmailList and network for Network models are unique you can do the following, if not and there are multiple entries using get will raise an Error.

name = cd.get('name')
email = cd.get('email')
email_list = EmailList.objects.get(email=email)
network = Network.objects.get(network=email_list.network)

User.object.create(name=name, email=email, network=network)

Upvotes: 3

Related Questions