I'm trying to integrate Django-Geoposition package into my Django project. I have my model:
class Post(models.Model):
position = GeopositionField(default= Geoposition(40.00,73.88))
votes= models.IntegerField(default=0)
date= models.DateTimeField(auto_now=False, auto_now_add=True)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
sound= models.FileField()
I've tried leaving no value for position, but I can't make migrations without a default value. I've also gone ahead and removed all instances of the model from the admin. Even with what I have above (which I found from another person with the same issue) I'm getting a
AttributeError: 'Geoposition' object has no attribute 'split'
when I try to make the migration. Anyone have any pointers?
I used blank=true so that I didn't have to put in a default value
Related
I've been building a Django website and included a UUID field "customer_id" in my initial "Customer" model. Finally, I decided to drop it. But when I try to delete it from my models.py, Django throws
SystemCheckError: System check identified some issues:
ERRORS:
<class 'accounts.admin.CustomerAdmin'>: (admin.E035) The value of 'readonly_fields[1]' is not a callable, an attribute of 'CustomerAdmin', or an attribute of 'accounts.Customer'.
Here is the code of models.py
from django.db import models
import uuid
# Create a base model to make sure we keep track of creation and edits
class ModelBaseClass(models.Model):
date_created = models.DateTimeField(auto_now_add=True, null=True)
date_modified = models.DateTimeField(auto_now=True, null=True)
class Meta:
abstract = True
# Create your models here.
class Customer(ModelBaseClass):
customer_id = models.UUIDField(default=uuid.uuid4, #this is the field i try to drop
editable=False,
unique=True)
name = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200, null=True)
def __str__(self):
return self.name
What I tried so far:
I suspect that this could be related to existing data or some other dependencies. So...
I deleted the sqlite database, deleted all migration files and ran
"python manage.py makemigrations" and "python manage.py migrate".
I ran python manage.py flush.
I also tried to change the editable=False to editable=True and migrate before dropping,
but it didn't change anything.
It's perhaps also worth mentioning that my "Customer" model a relation to another model.
Could someone explain me why Django is preventing me from deleting this field and how to resolve this?
Thanks! :)
Could someone explain me what's going on and how to resolve this?
As the error says, you have a model admin named CustomerAdmin. Indeed:
<class 'accounts.admin.CustomerAdmin'>: (admin.E035) The value of 'readonly_fields[1]' is not a callable, an attribute of 'CustomerAdmin', or an attribute of 'accounts.Customer'.
For the readonly_fields, it lists the customer_id, but since that field is no longer available, it raises the error.
I am trying to create a timestamp for my model Account, but I don't want my two time stamps (created_at and modified_at) to be editable or even viewable by the user. Everything works fine and as expected until I add editable=False to the created_at and modified_at fields. Here is my model:
class Account(models.Model):
account_name = models.CharField(max_length=25)
active = models.BooleanField(default=True)
created_at = models.DateTimeField(null=True, blank=True, editable=False)
modified_at = models.DateTimeField(null=True, blank=True, editable=False)
def save(self):
if self.id:
self.modified_at = datetime.datetime.now()
else:
self.created_at = datetime.datetime.now()
super(Account, self).save()
class Meta:
ordering = ('id',)
Here is the obscure error I get when I try to do anything (migrate, runserver, etc):
django.core.exception.FieldError: Unknown field(s) (created_at, modified_at) specified for Account
As soon as I remove editable=False from both fields, everything works fine. Is this a Django bug? Is there a better way to make the field non-viewable and non-editable by the user?
I am using Django 1.9 and Python 3.6.1. Thanks for the help, let me know if you need me to post anything else (views, serializers, etc).
EDIT
Full traceback: https://pastebin.com/YEQACX5z
Accounts Form:
class AccountForm(ModelForm):
class Meta:
model = Account
fields = ['account_name', 'active', 'created_at', 'modified_at']
You could just do,
created_at = models.DateTimeField(auto_now_add=True)
and
modified_at = models.DateTimeField(auto_now=True)
From the docs,
DateField.auto_now¶
Automatically set the field to now every time the object is saved. Useful for “last-modified” timestamps. Note that the current date is always used; it’s not just a default value that you can override.
The field is only automatically updated when calling Model.save(). The field isn’t updated when making updates to other fields in other ways such as QuerySet.update(), though you can specify a custom value for the field in an update like that.
DateField.auto_now_add¶
Automatically set the field to now when the object is first created. Useful for creation of timestamps. Note that the current date is always used; it’s not just a default value that you can override. So even if you set a value for this field when creating the object, it will be ignored.
So, no need to add editable=False, its already non-editable.
Also, remember to remove your save() method override since it's trying to modify those fields.
If you want to be able to modify this field, set the following instead of auto_now_add=True:
For DateField: default=date.today - from datetime.date.today()
For DateTimeField: default=timezone.now - from django.utils.timezone.now()
The default form widget for this field is a TextInput. The admin adds a JavaScript calendar, and a shortcut for “Today”. Includes an additional invalid_date error message key.
I have a pretty normal model:
class Nonce(models.Model):
key = models.CharField(_('key'), max_length=36, primary_key=True, blank=False)
token = models.ForeignKey('Token')
date_created = models.DateTimeField(_('date created'), blank=False, default='1970-01-01 00:00:00')
date_consumed = models.DateTimeField(_('date consumed'), blank=True, null=True)
created_by = models.IPAddressField(_('IP address'), blank=False, default='0.0.0.0')
consumed_by = models.ForeignKey('MyUser', blank=True, null=True, on_delete=models.SET_NULL)
def __unicode__(self):
return self.key
Many, many of these will be created and I only need to retain a fraction of these that are actually 'consumed' (used). Also, it is not evident from the model, but these will expire in 1 hour.
So, in the interest of not cluttering up my DB with a bunch of old nonces and to spare the application the work of periodically (frequently) deleting expired ones, I thought it best to just store them in RAM until they are consumed (if ever).
So, I've forked my code and I thought I'd just replace my code where I save() the objects that are created with save(commit=False), then store the object into RAM (Memcached). Later if a particular nonce is consumed, I'll then save() properly, otherwise, the object will just expire and be purged via Memcache.
Unfortunately, I'm getting the error: save() got an unexpected keyword argument 'commit' from Django at the line nonce.save(commit=False). Why?
I'm using Django 1.4.5 and Python 2.7.2.
Django's Model class doesn't have defined the save method that way. That is for ModelForms. The method signature for normal Model's save method is this one:
def save(self, force_insert=False, force_update=False, using=None):
You'll have to try another approach.
This is the dev's doc for Model's save method and this one is the version 1.4's
Hope this helps!
I have the following sample models:
class Note(models.Model):
text = models.TextField()
author = models.OneToOneField(User)
date_created = models.DateField(auto_now_add=True)
similar_note = models.ForeignKey("self", related_name='similar_note', null=True, blank=True)
Say there are two notes Winner and Loser.
Loser has a field similar_note that points to Winner Note.
When I delete any of the two, both gets deleted, how do I prevent this from happening?
I have tried doing the same from the django admin interface as well, it happens from there as well.
PS: I am using django1.2, please don't advice to upgrade, there are way too many constraints.
As mentioned here:
When Django deletes an object, by default it emulates the behavior of
the SQL constraint ON DELETE CASCADE -- in other words, any objects
which had foreign keys pointing at the object to be deleted will be
deleted along with it.
This cascade behavior is customizable via the on_delete argument to
the ForeignKey
Please check the on_delete parameter for model field:
user = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL)
So I'm building a Django application,
and these are a few models I have:
class MagicType(models.Model):
name = models.CharField(max_length=155)
parent = models.ForeignKey('self', null=True, blank=True)
class Spell(models.Model):
name = models.CharField(max_length=250, db_index=True)
magic_words = models.CharField(max_length=250, db_index=True)
magic_types = models.ManyToManyField(MagicType)
When syncing the models I'm getting this error:
AttributeError: 'ManyToManyField' object has no attribute '_get_m2m_column_name'
Is there a reason this is happening? How can I fix this?
Help would be very much appreciated.
EDIT:
I'm using django-evolution http://code.google.com/p/django-evolution/
I suggest you use django-extensions , this will give you a commnad sqldiiff that works better than evolution, because there is a problem creating the intermediate table between MagicType and MagicType.
I suggest you run the command sqlall yourapp and execute directly the sql code of the creation of the new intermediate table. Evolution doesn't it for you :(
Is MagicType declared in the same models file (and before) Spell?
Does magic_types = models.ManyToManyField('MagicType') work (with 'MagicType' quoted)?