Hi I have a model that has a return statement like this.
def __unicode__(self):
return u'Car from: %s' % self.car_from
If I call the model and print it, it shows.
mymodel = CarFromData.objects.filter(user = self.user )
<QuerySet [<CarFromData: Car from: CarRoom 1>]>
I would like to access the self.car_from in my view. So I can store the
CarRoom1 inside a variable.
I tried this way
x = mymodel.model.__name__
but that does not give me that string information.
car_from is nothing but an attribute to a CarFromData Model. So, its value can get in following way:
mymodel = CarFromData.objects.filter(user=self.user)
myobject = mymodel.first()
x = None
if myobject:
x = myobject.car_from
Related
Following this answer I wanted to add a linked column to my admin page,
class AnswerAdmin(admin.ModelAdmin):
list_display = ('__str__', 'link_to_question', 'time_created', 'time_updated', 'created_by', 'down_vote', 'up_vote')
def link_to_question(self, obj):
link = urlresolvers.reverse("admin:QnA_question_change",
args=[obj.question.id]) # model name has to be lowercase
text = obj.question.__str__
str = format_html("{}", text)
return mark_safe(u'%s' % (link, str))
class Meta:
model = Answer
but what I get in return is this:
<bound method Entry.__str__ of <Question: This is a question about technology?>>
I only want the "This is a question ..." part shown in my admin.
Sidenote:
when I use something like obj.question.text instead of a function it works smoothly.
It isn't clear why you are using format_html then passing the result to mark_safe. You should be able to do it in one step with format_html. This has the advantage of escaping text, in case a use has inserted malicious content.
link = urlresolvers.reverse(...)
text = obj.question
link_str = format_html('{}', link, text)
To call the __str__ method you need to call it with obj.question.__str__(). However, it's more pythonic to call str(obj.question) rather than obj.question.__str__(). In this case, I don't think you need to use str() at all, since you are using format_html.
just set the allow_tags = True property of the method.
class AnswerAdmin(admin.ModelAdmin):
list_display = ('__str__', 'link_to_question', 'time_created', 'time_updated', 'created_by', 'down_vote', 'up_vote')
def link_to_question(self, obj):
link = urlresolvers.reverse("admin:QnA_question_change",
args=[obj.question.id]) # model name has to be lowercase
return u'{1}'.format(link, obj.question)
link_to_question.short_description = u'Link'
link_to_question.allow_tags = True
Good day, I have the following problem that I'm trying to resolve. What I need to achieve is having the patient id generated as i run the app and print it. But it is not doing what I want. I want each time that I will run the app, and calling the view, a new id as to get generated and printed for now.
Here's a class that I have created to generate the id:
import uuid
class PatientId:
def __init__(self, id_number):
self.id_number = id_number
#staticmethod
def generate_patient_id_number():
prefix = 'HSCM'
generated_id = str(uuid.uuid4().hex[:6].upper())
return '%s-%s' % (prefix, generated_id)
and in my views.py,
from utilities.id_number import PatientId
# Create your views here.
def show_id(request, self):
id = PatientId(self).generate_patient_id_number()
print(id)
return render(request, 'index.html', {})
Will appreciate any help
Not sure why you have PatientId as a class, but with that given class you can use it like this, since generate_patient_id_number() is a static method
id = PatientId.generate_patient_id_number()
# id is e.g. 'HSCM-E9E10C'
You don't need a class for this
In Python you don't need to make everything into a class, so if you had a module called id_number you can simply put that function there (and then you can use it from anywhere, a view, a class, a Django model, etc)
# id_number.py
def generate_patient_id_number():
prefix = 'HSCM'
generated_id = str(uuid.uuid4().hex[:6].upper())
return '%s-%s' % (prefix, generated_id)
and use it like this
from utilities import id_number
def show_id(request):
id = id_number.generate_patient_id_number()
print(id)
return render(request, 'index.html', {})
Consider the following example model:
class MyModel(models.Model):
TYPE_ONE = 1
TYPE_TWO = 2
TYPE_CHOICES = (
(TYPE_ONE, "One"),
(TYPE_TWO, "Two"),
)
type = models.SmallIntegerField(choices=TYPE_CHOICES)
# ... other fields
This works well internally, as I now have a 'constant' which I can reuse throughout my code to refer to each type.
However, when this model gets serialized and sent to the client as JSON through a custom API Controller implementation, it turns the type into it's textual representation. It might look like this:
{
'id': 1,
'type': 'One'
}
This is fine, however I'd like to be able to set the field value based on this text version (the consumer of my API wants to be able to pass friendly strings, not ints).
When constructing a model instance, how can I set type to One, and have it automatically convert it into the relevant int?
Something like:
m = MyModel()
m.type = "One"
m.save() # throws a ValueError
Thanks
You can use this workaround:
m.type = dict((key,value) for (value,key) in MyModel.TYPE_CHOICES)['One']
You should make one property for it. So you can use whenever you want.
class MyModel(object):
TYPE_CHOICES = ((1, "One"), (2, "Two"))
type = models.SmallIntegerField(choices=TYPE_CHOICES)
def getx(self):
return self.type
def setx(self, val):
ch = filter(lambda y: y if y[1] == val else None, self.TYPE_CHOICES)
self.type = ch[0][0]
type_val = property(getx, setx)
then save like this.
m = MyModel()
m.type_val = "One"
m.save()
it will save into type.
Hopefully, it will work for you. :)
In the following code if the variable exist in the dictionary i want to save it, how to do this. This is the reason i wanted to convert str to variable in my previous question.
So the intention here is if there are n number of columns in the models, which i take in as a list and compare it with the request json di in this case. if the variable is found then i want to assign it to company object and save it
models.py
class Company(models.Model):
version = models.IntegerField()
old_comp = models.CharField()
views.py
c= Company()
li = ['version']
di = {'a':1,'version':2}
for data in li:
if data in di:
c.data = di[data] //gives an error since data is unknown to c
c.save()
Please try below code,
DISCLAIMER: I do not have experience with Django yet.
c = Company()
param_list = ['version']
param_vals = {'a':1,'version':2}
for param in param_list:
if param in param_vals:
setattr(c, param, param_vals[i])
c.save()
Please see the example:
class Company:
def version():
print '1.1.1'
if __name__ == '__main__':
b='version'
a=Company()
a.b(AttributeError: Company instance has no attribute 'b')
it is the same problem with your code, because the attr cannot use a variable, you can use c.version directly.
def index(request):
expiring_list = probe.objects.filter("isExpired=True")
output = ', '.join([p.serial for p in expiring_list])
return HttpResponse(output)
isExpired is a Boolean function. How should I modify the filter so that the filter does not raise a ValueError?
You are making the query in a wrong format.
Your query should be of the form:
expiring_list = probe.objects.filter(isExpired = True)
This was the query you needed to make in case isExpired was your model field. But since you say its a function, assuming that function is inside the class you need to get all the objects in the following way:
expiring_list = []
objects = probe.objects.all()
for obj in objects:
if obj.isExpired() == True:
expiring_list.append(obj)
The expiring_list will now contain all the objects of the model probe where isExpired function returns True
I think isExpired is not a field in your models, as reference to your previous question Refresh a field from another table [Django]
I think exp_date is the field which you are looking for.
Try this:
import datetime
def index(request):
expiring_list = probe.objects.filter(exp_date__lt=datetime.date.today())
output = ', '.join([p.serial for p in expiring_list])
return HttpResponse(output)