Django 'POST" returning 'Subscriber' object has no attribute 'title'

Question:

I am attempting to send a POST Request to add a ‘Subscriber’ to my database. The POST Request goes through without error.

I am Posting this

{
    "email":"[email protected]","campaign":1
}

and it returns

{
    "id": 2,
    "email": "[email protected]",
    "created_at": "2022-08-02T19:49:55.509018Z",
    "updated_at": "2022-08-02T19:49:55.509018Z",
    "campaign": 1
}

The ID is 2 because it is the second POST I have made

This is my Subscriber Class

class Subscriber(models.Model):
    campaign = models.ForeignKey(to = Campaign, on_delete=models.CASCADE)
    email = models.EmailField(max_length=254)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering=('-created_at',)

    def __str__(self):
        return self.title()

*** These are my current Serializers.py***

class CampaignSerializer(serializers.ModelSerializer):

    class Meta:
        model = Campaign
        fields = "__all__"


class SubscriberSerializer(serializers.ModelSerializer):

    class Meta:
        model = Subscriber
        fields = "__all__"

When I go to the Admin Panel at /admin and I click on my Subscribers that is when I get the error

AttributeError at /admin/Campaigns/subscriber/
‘Subscriber’ object has no attribute ‘title’

And I am unable to view the information posted.

If I remove

    def __str__(self):
        return self.title()

From my Subscriber Class, it works, however, it is displayed as
Subscriber object (1)
In the database, rather than the email name

So,

  1. Do I have to remove the
def __str__(self):
        return self.title()

From my Subscriber Class?

  1. How do I make the object name in the database the email itself?
Asked By: Timothy W. Times

||

Answers:

Subscriber doesn’t have a title field or attribute, hence the error. You need to return one of it’s attributes or an attribute of the campaign (which does have a title attribute), e.g.:

def __str__(self):
    return self.email

# or

def __str__(self):
    return self.campaign.title
Answered By: 0sVoid