I have these models:
class Video(models.Model):
suggestion = models.ForeignKey("VideoSuggestion", null=True)
title = models.CharField(max_length=300)
description = models.TextField(blank=True, null=True)
def __unicode__(self):
return u'%s %s' % (self.title, self.description)
class VideoSuggestion(models.Model):
sugestion_literal = models.CharField(max_length=100, unique=True)
def __unicode__(self):
return self.sugestion_literal
class VideoVariation(models.Model):
video = models.ForeignKey(Video, related_name='variations')
def __unicode__(self):
return u"Variations"
admin.py
class VideoVariationInline(admin.TabularInline):
model = VideoVariation
class VideoAdmin(admin.ModelAdmin):
inlines = [
VideoVariationInline,
]
sometimes, only sometimes, I am getting error
ValidationError([u'ManagementForm data is missing or has been tampered with'])
when I want to save a new object and save the existing one
what I noticed is, the Inline Form (VideoVariationInline) is missing in these cases.
I have read that this can be caused by __unicode__ method, but I have them all correct, right? what am I doing wrong?
Related
I fear that what I am trying to do might be impossible but here we go:
Among my models, I have the following
Class ParentCategory(models.Model):
name = models.CharField(max_length=128)
def __unicode__(self):
return self.name
Class Category(models.Model):
parentCategory = models.ForeignKey(ParentCategory, on_delete=models.CASCADE, )
name = models.CharField(max_length=128)
def __unicode__(self):
return self.name
Class Achievement(models.Model):
milestone = models.ForeignKey(Milestone, on_delete=models.CASCADE)
description = models.TextField( )
level_number = models.IntegerField()
completeion_method = models.ForeignKey(Category, on_delete = models.CASCADE, limit_choices_to={'parentCategory.name':'comp method'})
def __unicode__(self): # TODO:
return description[0,75] + '...'
I know the completion method field throws an error because it is not correct syntax. But is there a way to achieve the wanted result using a similar method?
Maybe this will work:
limit_choices_to={'parentCategory__name': 'comp method'}
I would like to request some assistance regarding this matter,
I am fairly new to django and I like it so far.
I have the following model:
class Courses_list(models.Model):
Abbreviation = models.CharField(max_length=100, unique=True)
Course = models.CharField(max_length=100, unique=True)
def save(self, force_insert=False, force_update=False):
self.Abbreviation = self.Abbreviation.upper()
super(Courses_list, self).save(force_insert, force_update)
def __unicode__(self):
return self.Abbreviation
class Job_Posting(models.Model):
Job_Position = models.CharField(max_length=30, null=True, unique=True)
def __unicode__(self):
return self.Job_Position
class Educational_Requirement(models.Model):
fkey = models.ForeignKey('Job_Posting')
Course = models.ForeignKey('Courses_list')
And form:
class CustomField(forms.ModelChoiceField):
def label_from_instance(self, obj):
return obj.Course
class SampleForm(ModelForm):
COURSE = CourseField(queryset=Educational_Requirement.objects.all())
I am saving at:
class MyModel(ModelForm):
course = models.CharField(max_length=50, null = True, blank = True)
In the frontend of my test app SampleForm shows the Course as choices but how do I get the actual value of Course and save it? Because when I view my saved COURSE in the admin it displays Educational_Requirement Object instead of the value I have seen on the dropdown. I can't use __unicode__ at Educational_Requirement as it would raise an error.
I have updated my answer based on your updated question.
Why not use a ManyToManyField and let Django's ORM handle the educational_requirement relationship for you? This way you can use Django's reverse lookup to handle the ForeignKey's name.
class Courses_list(models.Model):
Abbreviation = models.CharField(max_length=100, unique=True)
Course = models.CharField(max_length=100, unique=True)
def save(self, force_insert=False, force_update=False):
self.Abbreviation = self.Abbreviation.upper()
super(Courses_list, self).save(force_insert, force_update)
def __unicode__(self):
return self.Abbreviation
class Meta:
verbose_name = 'Course'
verbose_name_plural = 'Courses'
class Job_Posting(models.Model):
Job_Position = models.CharField(max_length=30, null=True, unique=True)
educational_requirement = models.ManyToManyField(Courses_list)
def __unicode__(self):
return self.Job_Position
class Meta:
verbose_name = 'Job Position'
verbose_name_plural = 'Job Positions'
I have one to many relationship with model Year and it has a foreign key with another model Compound. I am trying to get the Django admin widget to include the class name so that it can be pulled from the drop down /autocomplete.
I have it something like
def __unicode__(self):
return u'(%s) %d' % (self.compound.compound_name, self.year)
But this doesn't return the compound name as I expect but all attribute in the model compound.
class Year(models.Model):
compound = models.ForeignKey('Compound', blank=False, null=False)
year = models.PositiveSmallIntegerField(blank=True, null=True)
def __unicode__(self):
return u'(%s) %d' % (self.compound.compound_name, self.year)
class Compound(models.Model):
dif_id = models.CharField(max_length=50, blank=True, default='UnKnown')
type = models.CharField(max_length=50, blank=True, default='SM')
compound_name = models.CharField(max_length=100, blank=True, default='UnKnown')
phase = models.PositiveSmallIntegerField(db_index=True, default=0)
def __unicode__(self):
return u'%s %s %s %d' % (self.dif_id,self,type,self.compound_name,self.phase )
class Meta:
verbose_name_plural = 'Compounds'
Any idea how I should get the compound_name?
And also, I am looking to improve it by checking if the compound_name is Unknown the display the dif_id .
Thanks
Trying to access my json page I get this error!
AttributeError at /project/api/1.json
Got AttributeError when attempting to get a value for field `title` on serializer `TaskSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `RelatedManager` instance.
Original exception text was: 'RelatedManager' object has no attribute 'title'.
I have a Many to Many relationship with my models:
class Project(models.Model):
owner = models.ForeignKey('auth.User')
title = models.CharField(max_length=100)
slug = models.SlugField(unique=True)
created_date = models.DateTimeField(auto_now_add=True, auto_now=False)
updated_date = models.DateTimeField(auto_now_add=False, auto_now=True)
def __str__(self):
return self.title
def save(self, **kwargs):
super(Project, self, **kwargs).save()
self.slug = slugify(self.title)
super(Project, self, **kwargs).save()
def create(self):
pass
class Task(models.Model):
title = models.CharField(max_length=100)
description = models.TextField(blank=True)
completed = models.BooleanField(default=False)
project = models.ForeignKey('Project', related_name="tasks")
dependency = models.ManyToManyField('self', through='Dependency', null=True,
blank=True, through_fields=('task', 'sub_task'), symmetrical=False)
def sub_tasks(self, **kwargs):
qs = self.dependency.filter(**kwargs)
for sub_task in qs:
qs = qs | sub_task.sub_tasks(**kwargs)
return qs
def __str__(self):
return self.title
class Dependency(models.Model):
task = models.ForeignKey(Task, related_name="dependency_task")
sub_task = models.ForeignKey(Task, related_name="dependency_sub_task")
And these serializers:
class TaskSerializer(serializers.ModelSerializer):
class Meta:
model = Task
fields = ('id', 'title', 'project', 'completed',)
class ProjectSerializer(serializers.ModelSerializer):
tasks = TaskSerializer()
class Meta:
model = Project
fields = ('id', 'title', 'tasks',)
How can I get round this? RelatedManager tells me something is disagreeing with my M2M link, but why/how? I couldn't see anything here about Attribute Errors.
This question seems related, but setting many=False doesn't do anything.
AttributeError with Django REST Framework and MongoEngine
In that question they set many=False. You do have a Many-to-Many, so set many=True It's that simple.
In fact if you look closely, that's how the example shows you to do it:
class TrackListingField(serializers.RelatedField):
def to_representation(self, value):
duration = time.strftime('%M:%S', time.gmtime(value.duration))
return 'Track %d: %s (%s)' % (value.order, value.name, duration)
class AlbumSerializer(serializers.ModelSerializer):
tracks = TrackListingField(many=True)
class Meta:
model = Album
fields = ('album_name', 'artist', 'tracks')
See how the tracks listing field has the many=True attribute? Do that.
I had a similar issue when I missed out on specifying the related_name attribute to the definition of ForeignKeyField pointing to the Album model.
I's using django 1.6 and have a model for a blog but when saving the content I get category id can not be blank but I don't understand this error. I have tried looking at the code trying different things but it doesn't seem to be working.
class Category(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField(max_length=100)
description = models.TextField(null=True, blank=True)
class Meta:
verbose_name_plural = "Categories"
def __unicode__(self):
return '%s' % self.title
#permalink
def get_absolute_url(self):
return ('view_category', None, {'slug': self.slug})
class Blog(models.Model):
user = models.ForeignKey(User)
title = models.CharField(max_length=100, unique=True)
slug = models.SlugField(max_length=100, unique=True)
description = models.TextField(max_length=2000)
extended = models.TextField(null=True, blank=True)
category = models.ForeignKey(Category)
created = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
class Meta:
verbose_name = 'Blog post'
verbose_name_plural = 'Blog posts'
ordering = ('-updated',)
def __unicode__(self):
return '%s' % self.title
#permalink
def get_absolute_url(self, ):
return('view_questions', None, {'slug': self.slug,})
def save(self):
super(Blog, self).save()
if not self.slug:
self.slug = '%d/%s' % (
self.pk, slugify(self.title)
)
super(Blog, self).save()
when saving the content I get category id can not be blank but I don't
understand this error.
category = models.ForeignKey(Category)
That line means that a blog post must belong to a category. In your blog table, the category foreign key is called category_id.
You can either make sure to add a category; blog.category = Category.objects.get(...) for example OR you can make the category optional:
category = models.ForeignKey(Category, blank=True, null=True)