Django: modelchoicefield with multiple modelfields - python

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'

Related

Django many to many with additional field not working

I am new to Django and followed this to write my models.py file:
class Coin(models.Model):
name = models.CharField(max_length=50, unique=True)
class Meta:
verbose_name = 'coin'
verbose_name_plural = 'coins'
ordering = ['name']
def __str__(self):
return self.name
class PublicPortfolioManager(models.Manager):
def get_queryset(self):
qs = super(PublicPortfolioManager, self).get_queryset()
return qs.filter(is_public=True)
class Portfolio(models.Model):
title = models.CharField('title', max_length=255)
date_created = models.DateTimeField('date created')
date_updated = models.DateTimeField('date updated')
is_public = models.BooleanField('public', default=True)
owner = models.ForeignKey(User, verbose_name='owner',
related_name='portfolio')
coins = models.ManyToManyField(Coin, through='CoinInfo')
objects = models.Manager()
public = PublicPortfolioManager()
def __str__(self):
return '%s' % (self.title)
def save(self, *args, **kwargs):
if not self.id:
self.date_created = now()
self.date_updated = now()
super(Portfolio, self).save(*args, **kwargs)
class CoinInfo(models.Model):
coin = models.ForeignKey(Coin)
portfolio = models.ForeignKey(Portfolio)
amount = models.FloatField(default=0.0)
#date_purchased = models.DateTimeField(auto_created=True)
Everything works as it should except when I want to save an instance of CoinInfo, then I get the following error: table hello_coininfo has no column named coin_id. I already flushed the database and ran makemigrations and migrate before creating the instances. What I am doing wrong?
There was a problem with applying the migrations, which caused the coin.id field to be not created in the db and therefore this problem occurred.

Django-autocomplete-light returns object names instead of corresponding field values

My problem whith django-autocomplete-light (dal 3) is that in the admin, instead of showing the choices corresponding tom my designated field (i.e. birth_nation see forms.py section), I always get a list of the str values of my queryset objects (see #models.py section) which is actually the last_name field.
# models.py
class MyModel(models.Model):
id_name = models.CharField(primary_key=True, max_length=255)
first_name = models.CharField(max_length=255, blank=True, null=True)
middle_name = models.CharField(max_length=255, blank=True, null=True)
last_name = models.CharField(max_length=255)
birth_city = models.CharField(max_length=255, blank=True, null=True)
birth_nation = models.CharField(max_length=255, blank=True, null=True)
def __str__(self):
return self.last_name
class Meta:
managed = False
db_table = 'mytable'
# forms.py
class MyModelForm(forms.ModelForm):
birth_nation = forms.ModelChoiceField(
queryset=MyModel.objects.all(),
widget=autocomplete.ModelSelect2(url='country-autocomplete',
attrs={'data-minimum-input-length': 2}
)
)
class Meta:
model = MyModel
fields = ('__all__')
# views.py
class MyModelAutocomplete(autocomplete.Select2QuerySetView):
def get_queryset(self):
if not self.request.user.is_authenticated():
return MyModel.objects.none()
qs = MyModel.objects.all()
if self.q:
qs = qs.filter(birth_nation__istartswith=self.q)
return qs
Obviously, I want to get my choices that correspond to the birth_nation, what is wrong in my code?
try this:
def __str__(self):
return self.birth_nation
Autocomplete return value is a query object. If you want to see specific field in the object, write that field in your model class or change your autocomplete class return value.

List posts that fall under a particular catgeory in Django 1.9

I am working on a blog like project but different and I have recently started learning Django. So, in my app we have categories and tags as well. Now there's an Entry model which has ManyToMany relation with both Category and Tag. Now I am trying to get all the Entries which falls under a particular category, it's a similar feature that we have in blogs.
Following is my Tag and Category Model.
class CategoryQuerySet(models.QuerySet):
def category_menu(self):
return self.filter(intopmenu=True)
def top_catgories(self):
return self.order_by("views")[:5]
class Category(models.Model):
name = models.CharField(max_length=50, unique=True)
views = models.IntegerField(default=0)
intopmenu = models.BooleanField(default=False)
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
slug = models.SlugField(unique=True)
objects = CategoryQuerySet.as_manager()
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
super(Category, self).save(*args, **kwargs)
def __str__(self):
return self.name
class Meta:
verbose_name = "Entry Category"
verbose_name_plural = "Entry Categories"
ordering = ["created"]
class Tag(models.Model):
name = models.CharField(max_length=20)
slug = models.SlugField(max_length=200, unique=True)
def __str__(self):
return self.slug
Following is my Entry Model.
class EntryQuerySet(models.QuerySet):
def published(self):
return self.filter(publish=True)
def most_liked(self, num):
return self.order_by("-likes")[:num]
def most_views(self, num):
return self.order_by('-views')[:num]
class Entry(models.Model):
image = models.ImageField(upload_to='entries_images/', null=True)
image_alt = models.CharField(max_length=200, blank=True)
name = models.CharField(max_length=50, blank=True)
text = models.CharField(max_length=500, unique=True)
views = models.IntegerField(default=0)
likes = models.IntegerField(default=0)
publish = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
source = models.URLField(blank=True)
slug = models.SlugField(unique=True)
categories = models.ManyToManyField(Category)
tags = models.ManyToManyField(Tag)
objects = EntryQuerySet.as_manager()
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
super(Entry, self).save(*args, **kwargs)
def __str__(self):
return self.text
class Meta:
verbose_name = "Entry"
verbose_name_plural = "Entries"
ordering = ["created"]
In my urls.py I have the following url to view all entries by that fall under a particular category.
url(r'^category/(?P<category_slug>[\w\-]+)/$', views.category, name='category'),
Apparently, I don't understand how to write the view to retrieve list of all the entries falling under particular category or tag. Any help will be appreciated. I did refer many blog posts on the web regarding my problem and also searched SO, 1 is a similar question I found but that didn't help much.
try:
def category(request,category_slug):
category = get_object_or_404(Category,slug=category_slug)
return render(request,'template_name.html',{'category':category,'posts':category.entry_set.all()})
More information on https://docs.djangoproject.com/en/1.9/topics/db/examples/many_to_many/

django admin - sometimes inlines is missing

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?

Django: When saving issue

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)

Categories