Assuming that I have such model
COLORS= (
('R', 'Red'),
('B', 'Yellow'),
('G', 'White'),
)
class Car(models.Model):
name = models.CharField(max_length=20)
color= models.CharField(max_length=1, choices=COLORS)
It displays as a selectbox in the admin panel however I would like my admin-user to multi select those colors like many-to-many relationship, how can this be achieved without a ('RB', 'Red&Blue'),
type of logic
What is @property in Django? Here is how I understand it: @property is a decorator for methods in a class that gets the value in the method. But, as I understand it, I can just call the method like normal and it will get it.
What is ForeignKey in Django? ForeignKey is a Field (which represents a column in a database table), and it's used to create many-to-one relationships within tables. It's a standard practice in relational databases to connect data using ForeignKeys.
I've constructed a complete working example with meaningful models. It works perfect. I've tested it on Python 3.4.x and Django 1.8.4. At first I run admin panel and create records for each option in Thema model
models.py
from django.db import models
class Author(models.Model):
fname = models.CharField(max_length=50)
lname = models.CharField(max_length=80)
def __str__(self):
return "{0} {1}".format(self.fname, self.lname)
class Thema(models.Model):
THEME_CHOICES = (
('tech', 'Technical'),
('novel', 'Novel'),
('physco', 'Phsycological'),
)
name = models.CharField(max_length=20,choices=THEME_CHOICES, unique=True)
def __str__(self):
return self.name
class Book(models.Model):
name = models.CharField(max_length=50)
author = models.ForeignKey(Author)
themes = models.ManyToManyField(Thema)
def __str__(self):
return "{0} by {1}".format(self.name,self.author)
forms.py
from django import forms
from .models import *
class BookForm(forms.ModelForm):
themes = forms.ModelMultipleChoiceField(queryset=Thema.objects, widget=forms.CheckboxSelectMultiple(), required=False)
admin.py
from django.contrib import admin
from .models import *
from .forms import *
@admin.register(Author)
class AuthorAdmin(admin.ModelAdmin):
pass
@admin.register(Book)
class BookAdmin(admin.ModelAdmin):
form = BookForm
@admin.register(Thema)
class ThemaAdmin(admin.ModelAdmin):
pass
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With