coercing to Unicode: need string or buffer, NoneType found - django

I am making an Ajax request into views as follows:
def all_json_models(request):
data = {}
try:
isp = request.GET['status']
present_isp = Priority.objects.filter(ispname = isp)
isp_count = MultiWAN.objects.all()
# data['latest_no_rules'] = latest_no_rules
#data['present_isp'] = present_isp
data['isp_count'] = isp_count
return HttpResponse(simplejson.dumps(data))
my models.py is like
class MultiWAN(models.Model):
isp_name = models.CharField(max_length=10)
description = models.TextField(null=True)
ip_address = models.IPAddressField(null=True)
subnet = models.IPAddressField(null=True)
gateway = models.IPAddressField(null=True)
nameserver = models.ForeignKey('NameServer')
weight = models.IntegerField(null=False)
interface = models.CharField(max_length=5)
def __unicode__(self):
"""
This function is to return the values we required.
Arguments:
- `self`:
"""
# return u'%s ' % (self.isp_name)
class NameServer(models.Model):
""" A Isp can have more than one nameserver so far we are declearing a seperate table
"""
name = models.IPAddressField(null=False)
class Priority(models.Model):
priority = models.IntegerField(null = True)
ispname = models.ForeignKey('MultiWAN')
rule = models.CharField(max_length=5,null=False)
From = models.IPAddressField(null=True)
To = models.IPAddressField(null=True)
def __unicode__(self):
return u'%s ' % (self.priority)
while making request i am getting the error:
"coercing to Unicode: need string or buffer, NoneType found"
What i am doing wrong here?

It's hard to tell without the full traceback (because it gives information about where in you code the exception is thrown).
The error message "coercing to Unicode: need string or buffer, NoneType found" means that, at some point, django tried to convert something to unicode and expected a string, but received None. This means that either you call a function passing None instead of a string, or one of you methods returns None instead of a string.
In the code you showed us, MultiWAN.__unicode__ seems ill-defined. Maybe the error stems from this ?

Related

For each item update database

I'm a total beginner with Python/Django and trying to understand why this isn't working. I have a function that contains a for loop, doing some logic and then updating a model. but when I have more than 1 item in the loop I get a UNIQUE constraint failed: app_token.token_name error.
So I think I'm misunderstanding how the loop is working?
function
tokens = Token.objects.all()
for item in tokens:
if item.token_contract_address is not None:
token = Token.objects.get(pk=item.id)
parameters = {
'address':token.token_contract_address
}
session = Session()
session.headers.update(headers)
response = session.get(url, params=parameters)
resp = json.loads(response.text)
token_id = (resp['data'][next(iter(resp['data']))]['id'])
logo = (resp['data'][next(iter(resp['data']))]['logo'])
url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest'
parameters = {
'id':token_id
}
session = Session()
session.headers.update(headers)
response = session.get(url, params=parameters)
id = str(token_id)
price = (json.loads(response.text)['data'][id]['quote']['USD']['price'])
market_cap = (json.loads(response.text)['data'][id]['quote']['USD']['market_cap'])
change = (json.loads(response.text)['data'][id]['quote']['USD']['percent_change_24h'])
r = Token.objects.update(token_capture_date = formatedDate, token_price = price, token_name=item.token_name )
I'm expecting the this Token.objects.update(token_capture_date = formatedDate, token_price = price, token_name=item.token_name ) to update the model based on the item loop?
The model is very simple:
class Token(models.Model):
token_name = models.CharField(max_length=50, blank=False, unique=True)
token_slug = models.CharField(max_length=50, blank=True,null=True)
token_price = models.FloatField(blank=True,null=True)
token_capture_date = models.DateField(blank=True,null=True)
token_contract_address = models.CharField(max_length=50, blank=True,null=True)
def __str__(self):
return str(self.token_name)
I'm using the update on the objects and have tried removing the token_name, and tried using token.token_name
If I remove token_name= it updates both items in the database with the same values? which makes me think its this line r = Token.objects.update(token_capture_date = formatedDate, token_price = price, token_name=item.token_name ) do i need to apply some kinda of filter?
Thanks
I believe that by calling Token.objects.update() you actually end up trying to update all Token objects. Since token_name has to be unique, and you are giving it the same name as another Token object it throws that error.
Since you are already in a for loop, you can simply update the token that is currently being processed.
My suggestion would be to use this code instead:
item.token_capture_date = formattedDate
item.token_price = price
item.save()
This will make it so that the current token object which is being processed in the for loop has its respective field values updated and saved in the database.
Also, this line is unnecessary: token = Token.objects.get(pk=item.id) as we already have access to the token through the looping variable item.
Do let me know if this helps!

Trying to change IntegerProperty to FloatProperty of existing AppEngine DataStore. Getting error Indexed value must be at most 1500 bytes

BEFORE :
class Person(ndb.Model):
name = ndb.StringProperty()
age = ndb.StringProperty()
other_details = ndb.StructuredProperty(OtherDetails, 'othrdtl')
class OtherDetails(ndb.Model):
success = ndb.StringProperty()
qr_code = ndb.TextProperty()
AFTER:
class Person(ndb.Expando):
pass
rows_to_be_updated = []
for person in Person.all():
person.age = int(person.age)
rows_to_be_updated.append(person)
if len(rows_to_be_updated)>0:
ndb.put_multi_async(rows_to_be_updated)
#"When the above line is executed i am getting error"
Very AFTER:
class Person(db.Model):
name = db.StringProperty()
age = db.IntegerProperty()
other_details = ndb.StructuredProperty(OtherDetails, 'othrdtl')
As per the datastore document, the TextProperty is unindexed by default. What is the reason for the error? I have tried making explicit Indexed=False (ndb.TextProperty(indexed= False)) but didn't work.
Instead of trying to go through an expando model, you might consider using a different name in your database than in your model.
E.g. after
class Person(ndb.Model):
name = ndb.StringProperty()
string_age = ndb.StringProperty('age')
age = ndb.IntegerProperty('int_age')
other_details = ndb.StructuredProperty(OtherDetails, 'othrdtl')
Then you could use a hook to ensure that Person.age is always set, e.g.
class Person(ndb.Model):
#classmethod
def _post_get_hook(cls, key, future):
p = future.get_result()
if p and not p.age:
p.age = int(p.string_age)

django filter data and make union of all data points to assignt to a new data

My model is as follows
class Drawing(models.Model):
drawingJSONText = models.TextField(null=True)
project = models.CharField(max_length=250)
Sample data saved in drawingJSONText field is as below
{"points":[{"x":109,"y":286,"r":1,"color":"black"},{"x":108,"y":285,"r":1,"color":"black"},{"x":106,"y":282,"r":1,"color":"black"},{"x":103,"y":276,"r":1,"color":"black"},],"lines":[{"x1":109,"y1":286,"x2":108,"y2":285,"strokeWidth":"2","strokeColor":"black"},{"x1":108,"y1":285,"x2":106,"y2":282,"strokeWidth":"2","strokeColor":"black"},{"x1":106,"y1":282,"x2":103,"y2":276,"strokeWidth":"2","strokeColor":"black"}]}
I am trying to write a view file where the data is filtered based on project field and all the resulting queryset of drawingJSONText field are made into one data
def load(request):
""" Function to load the drawing with drawingID if it exists."""
try:
filterdata = Drawing.objects.filter(project=1)
ids = filterdata.values_list('pk', flat=True)
length = len(ids)
print(list[ids])
print(len(list(ids)))
drawingJSONData = dict()
drawingJSONData = {'points': [], 'lines': []}
for val in ids:
if length >= 0:
continue
drawingJSONData1 = json.loads(Drawing.objects.get(id=ids[val]).drawingJSONText)
drawingJSONData["points"] = drawingJSONData1["points"] + drawingJSONData["points"]
drawingJSONData["lines"] = drawingJSONData1["lines"] + drawingJSONData["lines"]
length -= 1
#print(drawingJSONData)
drawingJSONData = json.dumps(drawingJSONData)
context = {
"loadIntoJavascript": True,
"JSONData": drawingJSONData
}
# Editing response headers and returning the same
response = modifiedResponseHeaders(render(request, 'MainCanvas/index.html', context))
return response
I runs without error but it shows a blank screen
i dont think the for function is working
any suggestions on how to rectify
I think you may want
for id_val in ids:
drawingJSONData1 = json.loads(Drawing.objects.get(id=id_val).drawingJSONText)
drawingJSONData["points"] = drawingJSONData1["points"] + drawingJSONData["points"]
drawingJSONData["lines"] = drawingJSONData1["lines"] + drawingJSONData["lines"]

Django Test: type object has no attribute 'objects'

In my web application, I have locations and respective opening hours. The OpeningHours model looks as follows:
class OpeningHours(models.Model):
location = models.ForeignKey(
Location, related_name='hours', on_delete=models.CASCADE)
weekday = models.PositiveSmallIntegerField(choices=WEEKDAYS, unique=True)
from_hour = models.PositiveSmallIntegerField(choices=HOUR_OF_DAY_12)
to_hour = models.PositiveSmallIntegerField(choices=HOUR_OF_DAY_12)
class Meta:
ordering = ('weekday', 'from_hour')
unique_together = ('weekday', 'from_hour', 'to_hour')
def get_weekday_display(self):
return WEEKDAYS[self.weekday][1]
def get_hours_display(self):
return '{} - {}'.format(HOUR_OF_DAY_12[self.from_hour][1], HOUR_OF_DAY_12[self.to_hour][1])
def get_start_hour_display(self):
return HOUR_OF_DAY_12[self.from_hour][1]
def get_end_hour_display(self):
return HOUR_OF_DAY_12[self.to_hour][1]
def __str__(self):
return '{}: {} - {}'.format(self.get_weekday_display(),
HOUR_OF_DAY_12[self.from_hour][1], HOUR_OF_DAY_12[self.to_hour][1])
I'm trying to test a model similar to how I have successfully tested other models in my application:
class OpeningHours(TestCase):
def create_opening_hours(self, weekday=1, from_hour=12, to_hour=15):
self.location = create_location(self)
return OpeningHours.objects.create(location=self.location, weekday=weekday, from_hour=from_hour, to_hour=to_hour)
def test_opening_hours(self):
oh = self.create_opening_hours()
self.assertTrue(isinstance(oh, OpeningHours))
self.assertTrue(0 <= oh.from_hour <= 23)
self.assertTrue(0 <= oh.to_hour <= 23)
self.assertTrue(1 <= oh.weekday <= 7)
, but when running the test I get this error message:
Traceback (most recent call last):
File "<app_path>/tests.py", line 137, in test_opening_hours
oh = self.create_opening_hours()
File "<app_path>/tests.py", line 134, in create_opening_hours
return OpeningHours.objects.create(location=self.location, weekday=weekday, from_hour=from_hour, to_hour=to_hour)
AttributeError: type object 'OpeningHours' has no attribute 'objects'
I assume this could have to do with the ordering or unique_together metadata, but not sure how to solve this... any pointers in the right direction very much appreciated.
You have given OpeningHours name to your test class as well as to the model class. So change the name of the test class to anything other than OpeningHours will solve the mentioned issue.

django: Class-based Form has no errors but is not valid. What is happening?

I have a form which is returning False from .is_valid(), but .errors and .non_field_errors() appear to be empty. Is there any other way to check out what might be causing this?
In case it's a problem with my logging code, here it is:
logger.debug('form.non_field_errors(): ' + str(form.non_field_errors()))
logger.debug('form.errors: ' + str(form.errors))
My form code:
class IncorporateForm(forms.Form):
type_choices = (("LTD", "Private company limited by shares"),
("LTG", "Private company limited by guarantee"),
("PLC", "Public limited company"),
("USC", "Unlimited company with share capital"),
("UWS", "Unlimited company without share capital"))
country_choices = (("EW", "England and Wales"),
("CY", "Wales"),
("SC", "Scotland"),
("NI", "Northern Ireland"))
articles_choices = (("MOD", "Model articles"),
("AMD", "Model articles with amendments"),
("BES", "Entirely bespoke articles"))
name = forms.CharField(initial = "[name] limited")
registered_office = forms.CharField(widget=forms.Textarea,
label='Registered office address')
registration_country = forms.ChoiceField(choices=country_choices,
widget=forms.RadioSelect(renderer=SaneRadioField))
company_type = forms.ChoiceField(choices=type_choices,
widget=forms.RadioSelect(renderer=SaneRadioField), initial="LTD")
articles_type = forms.ChoiceField(choices=articles_choices,
initial='MOD',
widget=forms.RadioSelect(renderer=SaneRadioField))
restricted_articles = forms.BooleanField()
arts_upload = forms.FileField(label='Articles to upload')
My view code (to the point where I detect that the form is not valid):
def incorporate_view(request):
form = IncorporateForm()
DirectorsFormset = forms.formsets.formset_factory(OfficerForm, extra=30)
CapitalFormset = forms.formsets.formset_factory(CapitalForm, extra=30)
HoldingFormset = forms.formsets.formset_factory(HoldingForm, extra=30)
AmendsFormset = forms.formsets.formset_factory(ArticlesAmendsForm, extra=50)
if request.method == 'POST':
#bind and validate
form.data = request.POST
guarantee_form = GuaranteeForm(data=request.POST)
directors_formset = DirectorsFormset(prefix='directors', data=request.POST)
capital_formset = CapitalFormset(prefix='capital', data=request.POST)
holding_formset = HoldingFormset(prefix='holding', data=request.POST)
amends_formset = AmendsFormset(prefix='amends', data=request.POST)
save_objects = [] # objects to be saved at the end if there is no error
user_objects = {} # keyed by email
individual_objects = {} # keyed by email?
if(not (form.is_valid() and guarantee_form.is_valid()
and directors_formset.is_valid()
and capital_formset.is_valid() and
holding_formset.is_valid() and
amends_formset.is_valid())):
dbg_str = """
form.is_valid(): %s
guarantee_form.is_valid(): %s
directors_formset.is_valid(): %s
capital_formset.is_valid(): %s
holding_formset.is_valid(): %s
amends_formset.is_valid(): %s
""" % (form.is_valid(), guarantee_form.is_valid(),
directors_formset.is_valid(),
capital_formset.is_valid(),
holding_formset.is_valid(),
amends_formset.is_valid())
logger.debug(dbg_str)
logger.debug('form.non_field_errors(): ' + str(form.non_field_errors()))
logger.debug('form.errors: ' + str(form.errors))
Assigning to form.data does not bind the form — you should pass the data dict when the object is constructed (or look into the code and see which flags are set, but that's probably not documented and therefore not recommended).