When trying to save the data in the DB I have this error:
sqlite3.InterfaceError: Error binding parameter 1 - probably unsupported type.
models.py
class Movie(Model):
title = CharField(max_length=255)
omdb = JSONField()
slug = SlugField(max_length=255, unique=True, allow_unicode=True)
views.py
omdb_data = get_movie(title) # returns response.json() from external API call
print(type(omdb_data['Title'])) # str
print(type(omdb_data)) # dict
movie = Movie(title=omdb_data['Title'],
omdb=omdb_data, slug=slugify(title))
movie.save() # crashing here
What could be wrong? I'm guess it's problem with title or omdb parameters (not sure if ID counts or not) but no idea whats wrong.
SQLite doesn't support all types data. It's in its name (Lite). You may try to convert to PostgreSQL or another complete database solution. Here is a tutorial for Django+Postgres but be careful, it's little bit outdated.
Related
I'm adding an additional column repath to the Django.admin site, according to the document, it oughts to work, but once I introduced re package to this function, things went wrong.
here's code sample:
class InfoAddrAdmin(ModelAdmin):
list_display = ('id', 'machineId', 'uptime', 'repath')
list_filter = ('machineId',)
def repath(self, obj):
res = re.search(r"10\.1\d+\.\d+\.\d+", obj.ipaddr)
return res.group()<-Exception comes from here
and the related Model is defined as:
class RemoteAddress(models.Model):
id = models.AutoField(primary_key=True)
machineId = models.CharField(max_length=32)
uptime = models.DateTimeField(default=now)
ipaddr = models.TextField()
A piece of text with lots of IP addresses(i.e. the result of command ipconfig) is stored in the ipaddr field, and that regex searchs for an IP with prefix like '10.1xx.xxx.xxx', which proved working fine.
The main error is:
AttributeError: 'NoneType' object has no attribute 'group'
Using debuging tools, the res is not a None, Just the opposite, it contains the correct value, I'm confused why django believes it is None.
Complete Error stack is avaliable at https://pastebin.com/8WUBdg1F
You may find some information from https://docs.djangoproject.com/en/3.1/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_display
I have a MongoEngine Document class Student..
class Student(Document):
db_id = StringField()
name = StringField()
score = IntField()
deleted = BooleanField(default=False, required=True)
I would like to query as
Student.objects.filter(score__gte=30)
But I'm getting a error like AttributeError: 'int' object has no attribute 'get'
Can someone please help me in how I can do this? Thank you!
The following (minimal) snippet works fine
from mongoengine import *
connect()
class Student(Document):
name = StringField()
score = IntField()
Student(name='Bob', score=35).save()
print(Student.objects(score__gte=30))
# output: [<Student: Student object>]
I don't have any problem to run your code, perhaps start from mine and build on top until you identify the culprit. I would also recommend to drop the existing mongo collection before you test this.
In fact, depending on where the error is fired (we don't have the stack trace so we can't tell), it could be that it fails when loading the existing mongo document (returned by your query) into the Student constructor
I am building a service that makes short URLs. I have the models:
from django.db import models
class ShortURL(models.Model):
url = models.CharField(max_length = 50)
class LongURL(models.Model):
name = models.CharField(max_length = 100, null=True)
url_to_short = models.ForeignKey(ShortURL)
I have already run the command: python manage.py migrate
If I open the interpreter, using python manage.py shell and run this code:
>>> from appshort.models import LongURL
>>> a = LongURL(name = 'hello_long_link')
>>> a.save()
then I get the error:
django.db.utils.IntegrityError: NOT NULL constraint failed: appshort_longurl.url_to_short_id
What did I do wrong?
class LongURL(models.Model):
name = models.CharField(max_length = 100, null=True)
url_to_short = models.ForeignKey(ShortURL)
The way you have set it up, the url_to_short foreign key is not optional. So when you try to save:
>>> a = LongURL(name = 'hello_long_link')
>>> a.save()
Django is trying to tell you that you didn't provide the url_to_short relation on your a model instance.
You'll need to either
Provide the ShortURL relation when you create the LongURL instance
Make the url_to_short relation optional with null=True, blank=True.
While creating an entry for LongURL you must create an object of ShortURL or filter out already existing (because ForeignKey field cannot be left blank). Additionally, you say that sometimes you have been able to achieve the desired behaviour. This can be so because at those places you would have got an object of ShortURL which is not null. However, the error in the discussion arises, when you try to send a null object during the creation of LongURL. For example:
...
short_url_obj = ShortURL.objects.filter(...).first()
# you have to ensure that this above query is not null
try:
new_long_url = LongURL(url_to_short=short_url_obj, name="some_name")
new_long_url.save()
except:
# if the short_url_obj is null
print("The short_url_obj was null, cannot save to database")
...
One can also use if-else block instead, but I would not advice that.
I'm a bit of a newbie in Python, so go easy on me. I'm writing an AJAX handler in Django. Everything's been pretty straight-forward on this until now. I've been banging my head against this bit for the better part of a day. I'd like to return a JSON string that contains a dict that contains a queryset:
#
# models.py
#
class Project(models.Model):
unique_name = models.CharField(max_length=32, unique=True)
title = models.CharField(max_length=255, blank=True)
description = models.TextField('project description', blank=True)
project_date = models.DateField('Project completion date')
published = models.BooleanField()
class ProjectImage(models.Model):
project = models.ForeignKey('Project', related_name='images')
image = models.ImageField(upload_to=get_image_path)
title = models.CharField(max_length=255)
sort_metric = models.IntegerField()
#
# views.py
#
...
projects = Project.Project.objects.filter(published=True)
...
response_dict({
'success' : True,
'maxGroups' : 5, # the result of some analysis on the projects queryset
'projects' : projects
});
# This one works if I remove 'projects' from the dict
# response = json.dumps( response_dict )
# This one works only on projects
# response = serializers.serialize( 'json', response_dict, relations=('images') )
return HttpResponse( response, mimetype='application/javascript' )
I've commented out the two serialization lines, because:
The first one seems to only work with 'simple' dicts and since projects is included in my dict, it fails with [<Project: Project object>] is not JSON serializable
The second one seems to only work with querysets/models and since the 'outer' part of my dict is non-model, it complains that 'str' object has no attribute '_meta'. Note that I am using the wadofstuff serializer with the understanding that it would resolve the OneToMany relationship as defined in my model. But even when I get this working by only serializing projects, I do not have any of my ProjectImages in the output.
QUESTION 1: What is the best way to serialize the whole response_dict? Surely, I'm not the first person to want to do this, right?
QUESTION 2: Why am I unable to get the ManyToOne relationship to work?
Many thanks for your help.
UPDATE: Just found this one: Django JSON Serialization with Mixed Django models and a Dictionary and it looked promising, but I get 'QuerySet' object has no attribute '_meta' =(
You can't serialize a python object like that. There is a section in the django documentation on what to do.
https://docs.djangoproject.com/en/dev/topics/serialization/#id2
Here is the key part to look at:
json_serializer.serialize(queryset, ensure_ascii=False, stream=response)
In my django app, I have some objects that cause the corresponding URL in the django admin to be non ascii. (for example: http://mysite/admin/myapp/myclass/Présentation/)
I can edit the object without any problem but when I save it I have the following error:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 24: ordinal not in range(128), HTTP response headers must be in US-ASCII format
The strange thing is that the object is correctly saved into the database.
Does anybody know how the Django admin manages unicode? Any info, pointer or idea that can help to fix this problem would be appreciated.
Thanks in advance
Update: Here is the code of the Model
class Plugin(models.Model):
"""Some subcontent that can be added to a given page"""
class Meta:
ordering = ['ordering']
name = models.CharField(max_length=32, primary_key=True)
div_id = models.CharField(default='rightcol', max_length=32)
published = models.BooleanField(default=True,
help_text=_("If this is not checked, it is not displayed on the page."))
ordering = models.IntegerField(default=1,
help_text=_("plugins are sorted with this number in ascending order"))
content = models.TextField(blank=True)
registration_required = models.BooleanField(_('registration required'),
help_text=_("If this is checked, only logged-in users will be able to view the page."))
def __unicode__(self):
return u"%s -- %s" % (self.name, self.div_id)
Update:
That's clear that non-ascii character are not recommended in an URL. That's the cause of my problem and I have changed that.
Does anybody know what is used by the Django admin to build the URL of an object. I guess that it is the primary key. Is it right? is there a way to force Django to use something else and to retrieve the object safely?
I'm pretty sure your database is probably using the latin1 encoding. Django supposes you have everything set as unicode (utf8).
To check this out, get into MySQL Shell and type:
mysql> show variables like 'char%';
If you see a bunch of latin1 (or any other encoding that isn't utf8, except binary), you'll have to do this:
Open up my.cnf and look for the [mysqld] section.
Make sure after tmpdir = /tmp, you have the following lines:
default-character-set=utf8
collation_server=utf8_unicode_ci
character_set_server=utf8
skip-external-locking
skip-character-set-client-handshake
Restart the server.
You'll have to recreate or manually edit the encoding of all databases and table you have, changing my.cnf only affects the databases that will be created.
Hope I've helped.
Edit: By the way, on which Django version are you on? Seems like this was a bug that was fixed on 1.1: http://code.djangoproject.com/ticket/10267
This link saved my day
you have to add unicode support for your admin in your models.py:
class MyModel (models.Model):
some_field = models.CharField(max_length=1000)
def __unicode__(self):
return u'%s'%(self.some_field)
there might be other problems such as: your system encoding is not utf8, your database encoding is not utf8 and ... which is mentioned in the link provided!
in your model, have you tried putting
class Model(models.Model):
def __unicode__(self):
return self.name ## having a model object named "name"
Not sure if this is the answer you are searhing for, but have you tried?
I am now using the default id as primary key for every class of my model. As a consequence, I don't have forbidden characters in the url when accessing objects from the admin site.
I do recommend to keep the default id as primary key in most cases