Sushant
Sushant

Reputation: 3669

Associating users with models django

I have a lot of models in model.py -

class Portfolio(models.Model):
  company = models.TextField(null=True)
  volume = models.IntegerField(blank=True)
  date = models.DateField(null=True)
  isin = models.TextField(null=True)

class Endday(models.Model):
  company = models.TextField(null=True)
  isin = models.TextField(null=True)
  eop = models.TextField(max_length=100000)

class Results(models.Model):
  companies = models.TextField(default=0)
  dates = models.DateField(auto_now_add=False)
  eodp = models.FloatField(null=True)
  volume = models.IntegerField(null=True)

class Sectors(models.Model):
  sector_mc = models.TextField(null=True)

class Insector(models.Model):
  foundation = models.ForeignKey(Sectors, null=True)
  name = models.TextField(null=True)
  value = models.FloatField(default=0)

class AreaLineChart(models.Model):
  foundation = models.ForeignKey(CompanyForLineCharts, null=True)
  date = models.DateField(auto_now_add=False)
  price = models.FloatField(null=True)

  class Meta:
    ordering = ['date']

I have more such models but as you can see from this snippet, they are not in any way related to any user.

Now I want to relate them to a particular user. In the views too, I was not classifying data per user in any way.

I make users from django admin with username and password and also generate a token for those users from admin. I can authenticate via username and password but from there I know I'd need to use permissions but how is what I do not know. Also, I have serializers that are associated to these models, I know I'd have to use permissions there too but again, I don't know how to. As much as I understand it has to be in someway like this-

@api_view(['GET'])
def searched_company_ohlc(request):
  if request.method == 'GET':

  // User.objects.get('username'=some_user) 
  //I guess.

  qs = SearchedCompanyOHLC.objects.all()
  serializer = SearchedCompanyOHLCSerializer(qs, many=True)
  return Response(serializer.data)

Also, I'm using angularJS at the front-end that POSTS username and password on a view with POST decorator to verify the credentials. Where to go from here?

Upvotes: 0

Views: 2429

Answers (2)

Dimitris Kougioumtzis
Dimitris Kougioumtzis

Reputation: 2439

in your models.py you can relate user like this for example

from django.contrib.auth.models import  User, Group
class Portfolio(models.Model):
 owner = models.ForeignKey(User,verbose_name = 'User',related_name='portfolios')
 company = models.TextField(null=True)
 volume = models.IntegerField(blank=True)
 date = models.DateField(null=True)
 isin = models.TextField(null=True)

Upvotes: 2

Daniel Roseman
Daniel Roseman

Reputation: 600051

This has nothing to do with permissions.

If you want to associate your model with a user, use a ForeignKey to the user model.

Upvotes: 1

Related Questions