0

I am working on one of my first Django projects and on one of the models, I needed a field that returns a list that I can loop through and use in my templates. I have been trying to make it happen right there in models.py because I learned from the tutorials that it is best to perform all data manipulation or logic in the models file and nothing of such should be done in the templates as the template is just for rendering already parsed data. I tried:

class Profile():
    '''More user information.'''
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    user.first_name = models.CharField(max_length=25)
    user.last_name = models.CharField(max_length=25)
    interests = models.CharField(max_length=200)
    user.interests = [interest.strip() for interest in interests.split(',')]

In the code snippet above, I tried splitting comma separated values input by the user to try and make a list of it but I got the error:AttributeError: 'TextField' object has no attribute 'split'. Since the models.Charfield() and models.TextField() don't return a string, how do I go about this? I use the sqlite db on my local.

xodeeq
  • 66
  • 4
  • What is `user.first_name = models.CharField(max_length=25)` supposed to do? – Willem Van Onsem Jul 11 '20 at 11:30
  • It's supposed to hold the first name of the user while user.last_name will be for the user's last name. I was going to create a ProfileForm to ask user for those information. @Willem – xodeeq Jul 11 '20 at 21:55

1 Answers1

0
  1. The user model already has first_name and last_name so you can remove
  2. If you want your user model to have the property interest you need to user custom user model
  3. For performing an action on a field before saving it example you splitting the interests you can override the save method for the model
Gaurav Jain
  • 146
  • 10