New to python, and trying to use __unicode_ to render a string representation. The code is part of Django model. How can I write __unicode__ of MyType so that in templates it output its representation as 123 - 123 South ....
class UsAddress(models.Model):
#other fields
zip = us_models.USPostalCodeField()
country = models.CharField(max_length=2)
phone = us_models.PhoneNumberField()
def __unicode__(self):
return self.zip + self.country + self.phone
class MyType(models.Model):
code = models.IntegerField()
address = UsAddress
def __unicode__(self):
return str(self.code) + " - " + unicode(self.address) #self.address.__unicode__()
Output:
<MyType: 219 - <class 'web.models.UsAddress'>>
EDIT
At least in my case, the problem was I didn't model the relationship. So I added it to UsAddress.
mt = models.ForeignKey(MyType)
Try this:
class MyType(models.Model):
code = models.IntegerField()
address = UsAddress
def __unicode__(self):
return u'%s - %s' % (self.code, self.address)
Here is the unicode method.
Then, you can just use it in your template like this:
<p>My object: {{ mytype_obj }}</p>
The output will be:
My object: 123 - 123 South ....
Related
I tried to create a table using a class that is not related to my database in django and this class is stored in models.py as shown below (InfoServer is the class). What I wanted to do is to use this class to populate my table using django_tables2. Add models.Model as a parameter is not an option because I don't want to save this class in the database.
Whenever I define the model = InfoServer in tables.py I got this error and I suppose it's because InfoServer did not take models.Model as a parameter.
TypeError: descriptor 'repr' of 'object' object needs an argument
Any help is appreciated.
models.py
class TestServeur(models.Model):
nom = models.CharField(max_length=200)
pid = models.CharField(max_length=200)
memoire = models.IntegerField(null=True)
class InfoServer:
# "This is a class to test my knowledge of python"
def __init__(self,p = '',c = 0,m = 0):
self.pid = p
self.cpu = c
self.memoire = m
def getData(self):
return ("A server with %s memory and %s cpu" % (self.cpu,self.memoire))
views.py
def index(request):
return HttpResponse("Hello, world. You're at the index.")
def cpu_view(request):
liste = []
proc1 = Popen(['ps','-eo','pid,%cpu,%mem,comm'], stdout=PIPE, stderr=PIPE)
proc2 = Popen(['grep','java'], stdin=proc1.stdout, stdout=PIPE)
proc1.stdout.close()
for line in iter(proc2.stdout.readlines()):
clean_line = line.decode("utf-8")
info_utiles = clean_line.split()
pid,cpu,mem,*rest = info_utiles
i1 = InfoServer(pid,cpu,mem)
liste.append(i1)
table = TestServeur(liste)
RequestConfig(request).configure(table)
return render(request, 'server/cpu.html', {'output': table})
tables.py
class TableServeur(tables.Table):
class Meta:
# model = InfoServer
fields = ['pid', 'memory', 'cpu']
template_name = 'django_tables2/bootstrap4.html'
As I can see, InfoServer class is not a Django Model. Also I don't think you need to use that directly anyway. So, you can simply provide a list with dictionary, and render it in template with table.
First, we need to update Table class and remove Meta class from it, as we are not going to use any django models.
class TableServeur(tables.Table):
pid = tables.Column()
memory = tables.Column()
cpu = tables.Column()
Now, adding a new object method to return dictionary from InfoServer class:
class InfoServer:
# "This is a class to test my knowledge of python"
def __init__(self,p = '',c = 0,m = 0):
self.pid = p
self.cpu = c
self.memoire = m
def getData(self):
return ("A server with %s memory and %s cpu" % (self.cpu,self.memoire))
def get_dict_data(self):
return {'pid': self.pid, 'cpu': self.cpu, 'memory': self.memoire}
Finally, update the view:
for line in iter(proc2.stdout.readlines()):
clean_line = line.decode("utf-8")
info_utiles = clean_line.split()
pid,cpu,mem,*rest = info_utiles
i1 = InfoServer(pid,cpu,mem)
liste.append(i1.get_dict_data())
table = TestServeur(liste)
return render(request, 'server/cpu.html', {'output': table})
More info can be found in documentation on how you can populate table with data.
Let's say I have the following class:
class Human(object):
def __init__(self, name, last_name):
self.name = name
self.last_name = last_name
def get_last_name(self):
return self.last_name
And I know I can define a __repr__ method for it:
def __repr__(self):
return "Human being, named " + str(self.name) + " " + str (self.last_name)
However, what if I want to define a separate representation for a lastname method, too? I.e., if this is a sample:
>>> me = Human("Jane", "Doe")
>>> me
Human being, named Jane Doe
>>> me.get_last_name()
'Doe'
…then I want the last output be not only the string 'Doe' itself but something like Human being's last name is Doe – how can it be done? How to define a __repr__ (or a __str__) method for a method?
Thanks.
You can not use a special attribute for a function or another attribute. In this case since you have self.last_name in your __init__ function, instead of returning it back in get_last_name() you can apply expected changes on last_name here and return the expected format.
class Human(object):
def __init__(self, name, last_name):
self.name = name
self.last_name = last_name
def get_last_name(self):
# return expected format
And you can directly access last_name if you want to see the raw data.
me = Human("Jane", "Doe")
print(me.last_name)
If you want readable representation override __str__ method. For obtain unambiguous output override __repr__
I have a function in a django model, this function is for calculating the two fields, but how I can obtain the function result,for show this in a django view
class Player(models.Model):
team = models.ForeignKey(Team)
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
gp = models.IntegerField(max_length=2) #games played
mp = models.IntegerField(max_length=4) #minutes played
def mpg(self): #minutes per game
return self.mp/self.gp
def __unicode__(self):
return self.first_name+' '+self.last_name
When I run "python manage.py shell" and try to pull up a player's
"mpg", I get:
>>> p = Player.objects.get(last_name='Durant')
>>> p
<Player: Kevin Durant>
>>> p.mp
1027
>>> p.gp
27
>>> p.mpg
<bound method Player.mpg of <Player: Kevin Durant>>
mpg is a method, and like all methods in Python, you need to actually call it to get its result:
p.mpg()
Class NickName(models.Model):
name = models.CharField()
def __unicode__(self):
return unicode(self.name)
Class Bob(models.Model):
bob_nickname = models.ManyToManyField(NickName)
def __unicode__(self):
return unicode(self.bob_nickname)
Number1. How would I get the __unicode__ for class Bob to display the actual FK name, rather than the <django.db.models.fields.related.ManyRelatedFieldsManager Object at 0Xdsfjk>?
EDIT: simply doing self.bob_nickname.all() seems to work fine. It aint pretty, but it displays the info: [<NickName: Ron>,<NickName: Randy>]
Number2. Also, how can I get the def __unicode__ to not escape \n? I'd like to create a multiline unicode string
Thank you!
Why don't you use values_list to get all related nick_names as list?
class Bob(models.Model):
bob_nickname = models.ManyToManyField(NickName)
def __unicode__(self):
return u'\n'.join(self.bob_nickname.values_list('name', flat=True))
I'm messing around with my first Django site and so far it's going good. I am now facing the challenge of getting some information from the DB. My model looks like this:
class Countries(models.Model):
country = models.CharField(max_length=100)
def __unicode__(self):
return self.country
class OrganisationTypes(models.Model):
organisation_type = models.CharField(max_length=100)
def __unicode__(self):
return self.organisation_type
class Organisations(models.Model):
organisation_name = models.CharField(max_length=200)
organisation_type = models.ForeignKey(OrganisationTypes)
country_of_origin = models.ForeignKey(Countries)
def __unicode__(self):
return self.organisation_name
class Locations(models.Model):
organisation = models.ForeignKey(Organisations)
country_of_location = models.ForeignKey(Countries)
tel_nr = models.CharField(max_length=15)
address = models.CharField(max_length=100)
def __unicode__(self):
return '%s - %s - %s - %s' % (self.organisation, self.country_of_location, self.tel_nr, self.address)
I now want to display a list of locations of which I want to display the organisation_name and the country_of_origin. To achieve this I wrote the following function:
def organisation_locations(requests, organisation_id):
org = Organisations.objects.get(id=organisation_id)
location_list = Locations.objects.filter(organisation=organisation_id).order_by('country_of_location')
output = '<br />'.join([str(loc.organisation)+' from '+str(org.country_of_origin) for loc in location_list])
return HttpResponse(output)
This works correctly, but it doesn't seem like the correct way of doing this. Since the Location table has a foreign key in the Organisations table which in turn has a foreign key in the Countries table I have this vague feeling that Django can do this in one "query" or lookup.
Am I correct in this feeling, or is my way indeed the correct way of doing this? All tips are welcome!
Can't you do:
location_list = Locations.objects\
.filter(organisation=organisation_id)\
.order_by('country_of_location')
output = '<br />'.join([str(loc.organisation)+' from '+str(loc.organisation.country_of_origin) for loc in location_list])
The organisation query isn't necessary. You can access organisation like this: localization.organisation.
What is not Djangonic in your code is the response. You should have a template and do return render_to_response :)