How to remove symbol in django [<Project:projectname>] - django

views.py
def passAuthProjFeature(request):
if request.method == 'POST':
author_name = request.POST['author_id']
project_id = request.POST['tcgproject_id']
feature_name = request.POST['tcgsearch_id']
project_name =Project.objects.filter(id=project_id)
project_name=str(project_name)
project_name = project_name.split[" "][1]
project_name = project_name.split[">"][0]
when i print project name it gives me in []
I want only projectname in variable

You get instance of Project class, but it seems that you need only one field of instance, for example 'name'. You can get this:
project = Project.objects.values('name').get(id=project_id)
project_name = project['name']

project_name =Project.objects.filter(id=project_id)
As you are using filter() method in the ORM query, it is returning the list of project objects.
I think better is to use the get() method in the query to get the desired result.
Assuming the below the model structure:
class Project(models.Model):
name = models.CharField(max_length=any numeric value)
......
Try this query:
project_name = Project.objects.get(id=project_id).name

Related

AttributeError: _auto_id_field Django with MongoDB and MongoEngine

I am using mongoengine with Django
Below is my Model class
class MyLocation(EmbeddedDocument):
my_id = IntField(required=True)
lat = GeoPointField(required=False)
updated_date_time = DateTimeField(default=datetime.datetime.utcnow)
My Views.py
def store_my_location():
loc = MyLocation(1, [30.8993487, -74.0145665])
loc.save()
When I am calling the above method I getting error AttributeError: _auto_id_field
Please suggest a solution
I suggest using the names when you save the location. Since class definition does not include how you put in these keys that is why we need to use the name to define them.
def store_my_location():
loc = MyLocation(my_id=1, lat=[30.8993487, -74.0145665])
loc.save()
This should work.
One more appraoch is to write everything in MyLocation class.
class MyLocation(EmbeddedDocument):
my_id = IntField(required=True)
lat = GeoPointField(required=False)
updated_date_time = DateTimeField(default=datetime.datetime.utcnow)
def create(my_id,lat):
location=MyLocation(my_id=my_id,lat=lat)
location.save()
return location
def store_my_location():
loc = MyLocation.create(1,[30.8993487, -74.0145665])

Get verbose name of foreign key from objects _meta dynamically in Django

For simplicity sake, with models like the following:
class Plan(models.Model)
name = models.CharField(max_length=255, verbose_name="Phone Plan Name")
monthly_charge = models.FloatField()
class Company(models.Model):
name = models.CharField(max_length=255, verbose_name="Company Full Name")
phone_plan = models.ForeignKey(Plan)
class Client(models.Model):
name = models.CharField(max_length=255, verbose_name="Client Full Name")
company = models.ForeignKey(Company)
Given a string, I want to know if there is an easy way to retrieve the verbose name of a model attribute even if that string traverses through foreign keys.
I know that I can get the verbose name of a Client attribute by
Client._meta.get_field("name").verbose_name
and this would result in "Client Full Name".
But what if I had the string "company__phone_plan__name", I cannot simply use
Client._meta.get_field("company__phone_plan__name").verbose_name
to arrive at "Phone Plan Name" as it yields an error.
These strings will be dynamic, so I am wondering what is the easiest way to arrive at the proper verbose name of an attribute, even if it traverses models?
This particular case is using Django 1.11
This is not so good answer but if you need what you want you can use this function:
def get_verbose_name(model, string):
fields = string.split('__')
for field_name in fields[:-1]:
field = model._meta.get_field(field_name)
if field.many_to_one:
model = field.foreign_related_fields[0].model
elif field.many_to_many or field.one_to_one or field.one_to_many:
model = field.related_model
else:
raise ValueError('incorrect string')
return model._meta.get_field(fields[-1]).verbose_name
This function gets model name and string and return verbose name
You can use it like so:
get_verbose_name(Client, 'company__phone_plan__name')
If you are working with instances of the models, then you could try this:
c = Client.objects.first()
# c._meta.get_field('company').verbose_name
# c.company._meta.get_field('phone_plan').verbose_name
c.company.phone_plan._meta.get_field('name').verbose_name
If you are working with classes only, then its a but more complex:
field_company = Client._meta.get_field('company')
field_phone_plan = field_company.rel.to._meta.get_field('phone_plan')
field_name = field_phone_plan.rel.to._meta.get_field('name')
field_name.verbose_name
# or one long line
s = Client._meta.get_field('company') \
.rel.to._meta.get_field('phone_plan') \
.rel.to._meta.get_field('name') \
.verbose_name
EDIT:
User #AndreyBerenda points out that the second option does not work for him in Django 2.1; I tested only in 1.11, which was specified in the question.

Django validate data when updating model with primary key

I am having trouble with updating fields of a model instance. The model is as follows:
class commonInfo(models.Model):
mothers_id = models.IntegerField(primary_key=True)
date = models.DateField()
data_collector = models.CharField(max_length=50)
Essentially, I just want to do this, but it won't work because commonInfo has a user defined primary key
commonInfo_form(request.POST or None).is_valid()
Since I am updating, I am overriding date and data_collector, but not mothers_id. So I would want to do something like this, but this specific code is not working
obj = commonInfo.objects.get(pk=commonInfo_id)
form = commonInfo_form(request.POST)
date = form.cleaned_data['data_collector'] #this line is not working
data_collector = form.cleaned_data['data_collector'] #this line is not working
obj.update(**{'date':date, 'data_collector':data_collector})
any ideas? I feel like it is just those two lines that I need to fix. Or if there is a more pythonic way or built method in Django?
Just validate with isinstance. so like,
if isinstance(request.POST['date'], datetime.date) and isinstance(request.POST['data_collector'], str):
# you might have to use getattr for request.POST here, I'm not sure
# and request.POST['date'] would have to be converted from a string to datetime.date I think
date = request.POST['date']
data_collector = request.POST['data_collector']
obj.update(**{'date':date, 'data_collector':data_collector})
The process for adding a record from a form is different from updating an existing instance. All you need to do differently is indicate which instance to bind the form to when you create it, ex:
obj = commonInfo.objects.get(pk=commonInfo_id)
form = commonInfo_form(request.POST, instance=obj)

Django SELECT (1) AS [a] FROM [my_table] WHERE ([my_table].[id] = ? AND NOT ([my_table].[id] = ? )) (1, 1)

Why is Django executing statements such as this:
SELECT (1) AS [a] FROM [my_table]
WHERE ([my_table].[id] = ?
AND NOT ([my_table].[id] = ? )) (1, 1)
This happens when calling is_valid() on a formset created the following way:
MyFormSet = modelformset_factory(Table, fields=['my_field'], extra=0)
my_form_set = MyFormSet(request.POST,
queryset=Table.objects.all())
where Table and MyForm are as simple as, say:
class Table(models.Model):
my_field = models.CharField(max_length=10)
class MyForm(forms.ModelForm):
class Meta:
model = Table
Hint: I looked at the call stack and the code responsible for it (in django/forms/models.py) is below:
def _perform_unique_checks(self, unique_checks):
import pdb; pdb.set_trace()
bad_fields = set()
form_errors = []
for unique_check in unique_checks:
# Try to look up an existing object with the same values as this
# object's values for all the unique field.
lookup_kwargs = {}
for field_name in unique_check:
lookup_value = self.cleaned_data[field_name]
# ModelChoiceField will return an object instance rather than
# a raw primary key value, so convert it to a pk value before
# using it in a lookup.
if isinstance(self.fields[field_name], ModelChoiceField):
lookup_value = lookup_value.pk
lookup_kwargs[str(field_name)] = lookup_value
qs = self.instance.__class__._default_manager.filter(**lookup_kwargs)
# Exclude the current object from the query if we are editing an
# instance (as opposed to creating a new one)
if self.instance.pk is not None:
qs = qs.exclude(pk=self.instance.pk)
Basically the pk is both included for the uniqueness check and excluded. Looks like Django can be smarter and avoid such inefficiency.
I haven't looked at it in detail, but I think you are right that Django could shortcut this query. Please file a ticket at http://code.djangoproject.com/.
Looks like this has been fixed already in trunk (by adding new functionality that also fixes this particular problem)

Save it if this RECORD is not exist?

Models.py
#.....
class FilterSave(models.Model):
def __unicode__(self):
return "%s" % (self.name)
name = models.CharField(max_length=50)
customer_type = models.CharField(max_length=20)
tag = models.CharField(max_length=10)
In my views.py
#......
def save_filter(self, filter_name, keyword_filter):
dict_json = eval(json.dumps(keyword_filter))
filter_saves = FilterSave.objects.all()
# Avoid record that already exist
filter_save = FilterSave(name=filter_name, customer_type=dict_json["customer_type"], tag=dict_json["tag"])
# I am trying ....
for fs in filter_saves:
if fs.name != filter_name:#just check for a field name
filter_save.save()
else:
print 'already exist '
More I tried
# Avoid name collision(just for name field not for a Record)
filter_save = FilterSave(name=filter_name, customer_type=dict_json["customer_type"], tag=dict_json["tag"])
exists = FilterSave.objects.filter(name=filter_name)
if not exists:
filter_save.save()
My problems here .I want to save a RECORD if it's not exist in table.Anybody Could help me what I am trying here?
thanks
Django has a convenience method get_or_create(defaults=None, **kwargs)
get_or_create
A convenience method for looking up an object with the given kwargs (may be empty if your model has defaults for all fields), creating one if necessary.
Returns a tuple of (object, created), where object is the retrieved or created object and created is a boolean specifying whether a new object was created.
Is that what you mean?