I want to define some fields for my model in another model. Here:
class Setting(models.Model):
name = models.CharField(max_length=255)
def __unicode__(self):
return self.name
class Option(models.Model):
name = models.CharField(max_length=255)
setting = models.ForeignKey(Setting)
def __unicode__(self):
return self.name
class Car(models.Model):
hsn = models.PositiveIntegerField("HSN", max_length=4)
tsn = models.PositiveIntegerField("TSN", max_length=3)
mileage = models.PositiveIntegerField("Kilometerstand")
settings = models.ManyToManyField(Setting)
In the admin I want to have every Settings.name as a field in CarAdmin with a select box of Options.name
How can I do this?
I've run accross a similar problem and solved it as below, I believe it should do the trick.
What you want is to have the Settings as inlines in your Car changeform and a M2M field pointing toward Options in the Setting Inline, overriding its widget to display it as checkboxes.
In your models.py:
class Option(models.Model):
name = models.CharField(max_length=255)
def __unicode__(self):
return self.name
class Car(models.Model):
hsn = models.PositiveIntegerField("HSN", max_length=4)
tsn = models.PositiveIntegerField("TSN", max_length=3)
mileage = models.PositiveIntegerField("Kilometerstand")
def __unicode__(self):
return self.hsn
class Setting(models.Model):
name = models.CharField(max_length=255)
options = models.ManyToManyField(Option, blank=True, null=True)
car = models.ForeignKey(Car, blank=True, null=True)
def __unicode__(self):
return self.name
In your admin.py :
from django.forms import CheckboxSelectMultiple
class OptionAdmin(admin.ModelAdmin):
pass
admin.site.register(Option, OptionAdmin)
class SettingInline(admin.TabularInline):
model = Setting
formfield_overrides = {
models.ManyToManyField: {'widget': CheckboxSelectMultiple},
}
class CarAdmin(admin.ModelAdmin):
inlines = [
SettingInline
]
admin.site.register(Car, CarAdmin)
There might be some caveats with this solution, such as common options for every setting or misplaced help text below checkboxes, I've not looked further but it should be fixable.
Related
I am learning Django so this is all very new to me. What I am trying to create is a bit of functionality in my admin panel that will allow me to create a layout like this.
Test
-Event1
--Property1
--Property2
--Property3
--Property4
-Event2
--Property1a
--Property2b
--Property3c
--Property4d
-Event3
--Property1aa
--Property2bb
--Property3cc
--Property4dd
-Event4
--Property1aaa
--Property2bbb
--Property3ccc
--Property4ddd
I want to have multiple tests. My current model setup looks like this:
from django.db import models
from django.forms import ModelForm
TYPE_CHOICES = (
("string", "string"),
("integer", "integer"),
("array", "array"),
("boolean", "boolean")
)
class Test(models.Model):
name = models.CharField(max_length=255)
description = models.CharField(max_length=255, blank=True)
class Meta:
verbose_name = 'Test'
verbose_name_plural = 'Tests'
def __str__(self):
return self.name
class Event(models.Model):
name = models.CharField(max_length=255)
test_id = models.IntegerField()
class Meta:
verbose_name = 'Event'
verbose_name_plural = 'Events'
def __str__(self):
return self.name
class Property(models.Model):
name = models.CharField(max_length=255)
property_type = models.CharField(max_length=20, choices=TYPE_CHOICES)
expected_value = models.CharField(max_length=255)
class Meta:
verbose_name = 'Property'
verbose_name_plural = 'Properties'
def __str__(self):
return self.name
class TestForm(ModelForm):
class Meta:
model = Test
fields = ['name', 'description']
I have my admin panel setup so that I can create multiple properties. But then when I go to the "Events" section in my admin panel I can only create events. I want to be able to pick the properties and add them to my event. Then I want to be able to go to the Test page and add the events to it.
A good example of what I am trying to create is a replica of this: http://jsonparser.tools/tests.php
you should define foreign keys for events and properties:
from django.db import models
from django.forms import ModelForm
TYPE_CHOICES = (
("string", "string"),
("integer", "integer"),
("array", "array"),
("boolean", "boolean")
)
class Test(models.Model):
name = models.CharField(max_length=255)
description = models.CharField(max_length=255, blank=True)
class Meta:
verbose_name = 'Test'
verbose_name_plural = 'Tests'
def __str__(self):
return self.name
class Event(models.Model):
name = models.CharField(max_length=255)
test = models.ForeignKey(Test,on_delete=models.CASCADE)
class Meta:
verbose_name = 'Event'
verbose_name_plural = 'Events'
def __str__(self):
return self.name
class Property(models.Model):
event = models.ForeignKey(Event,on_delete=models.CASCADE)
name = models.CharField(max_length=255)
property_type = models.CharField(max_length=20, choices=TYPE_CHOICES)
expected_value = models.CharField(max_length=255)
class Meta:
verbose_name = 'Property'
verbose_name_plural = 'Properties'
def __str__(self):
return self.name
class TestForm(ModelForm):
class Meta:
model = Test
fields = ['name', 'description']
this should solve your problem if not let me know happy to help.
I'm working on a project using Python(3.7) and Django(2.1) in which I have a model call Category which has a filed as parent of type ForeignKey to itself as self. It's displaying in the Django admin as a drop down, as there will be hundreds of PARENT categories, so we can't use a dropdown in such a situation, what I want to display a big table with a search option to select a category as parent.
Here's my Category model:
From models.py:
class Category(models.Model):
name = models.CharField(max_length=200)
slug = models.SlugField()
description = models.TextField(max_length=1000, default='')
parent = models.ForeignKey('self',
blank=True,
null=True,
related_name='children',
on_delete=models.CASCADE)
class Meta:
unique_together = ('slug', 'parent',)
verbose_name_plural = "categories"
def __str__(self):
full_path = [self.name]
k = self.parent
while k is not None:
full_path.append(k.name)
k = k.parent
return ' -> '.join(full_path[::-1])
And From admin.py:
#admin.register(Category)
class CatAdmin(admin.ModelAdmin):
filter = ('parent',)
class Media:
css = {
'all': ('assets/css/custom.css',),
}
so, how can I achieve my required scenario in Django admin?
Thanks in advance!
I just start to learn Django and I want to create a Product model with attributes, custom fields and custom field options. Custom field options exemple:
Line 1: [YOUR TEXT] | Custom field options: [FONT] [FONT SIZE] [...]
Line 2: [YOUR TEXT] | Custom field options: [FONT] [FONT SIZE] [...]
So I've created this models:
from django.db import models
from django.utils import timezone
class Product(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
sku = models.CharField(max_length=100)
slug = models.CharField(max_length=100)
price = models.DecimalField(max_digits=6, decimal_places=2)
active = models.BooleanField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.name
class ProductMeta(models.Model):
product = models.OneToOneField('Product')
title = models.CharField(max_length=100)
description = models.TextField(max_length=250)
class ProductImage(models.Model):
def upload_path(self, filename):
return 'static/uploads/images/%s%s' % (timezone.now().strftime('%Y/%m/%d/%Y%m%d_'), filename)
product = models.ForeignKey('Product')
name = models.CharField(max_length=100)
default = models.BooleanField()
image = models.ImageField(upload_to=upload_path)
def __unicode__(self):
return self.name
class ProductCharacteristic(models.Model):
product = models.ForeignKey('Product', related_name="characteristics")
name = models.CharField(max_length=100)
value = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class ProductAttribute(models.Model):
category = models.ForeignKey('ProductAttributeCategory')
products = models.ManyToManyField('Product', related_name="attributes")
name = models.CharField(max_length=100)
ordering = ['-category']
def __unicode__(self):
return u'%s : %s' % (self.category, self.name)
class ProductAttributeCategory(models.Model):
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class ProductAttributeValue(models.Model):
attribute = models.ForeignKey('ProductAttribute', related_name="values")
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class ProductCustomField(models.Model):
product = models.ForeignKey('Product', related_name="custom_fields")
name = models.CharField(max_length=100)
description = models.TextField(max_length=250)
def __unicode__(self):
return self.name
class ProductCustomFieldOption(models.Model):
fields = models.ManyToManyField('ProductCustomField', related_name="options")
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class ProductCustomFieldOptionValue(models.Model):
option = models.ForeignKey('ProductCustomFieldOption', related_name="values")
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
But now I don't know how to create the form in product details page in which the user can choose the product attributes (color, size...) and the product custom fields (and custom fields options). I've tried a lot of things but no results.
Can you help me please? :)
your question is unclear to me and your even more confusing. However see this if it helps
In your models.py
from django.db import models
from model_utils import Choices
colour_choices = ('Blue', 'Green')
class Product(models.Model):
name = models.CharField(max_length=100)
def __unicode__(self):
reuturn self.name
class ProductAttributes(models.Model):
product = models.Foreignkey(Product, related_name='products')
colour = models.CharField(choices=Choices(*colour_choices))
In your forms.py
from django import forms
from .models import Product, ProductAttributes
class ProductForm(forms.ModelForm):
class Meta:
model = Product
class ProdductAttributesForm(forms.ModelForm):
class Meta:
model = ProductAttributes
Write your views.py, urls.py and template accordingly
this method will give you a text box to enter products and drop-down for choosing color.
Hope it helped!
Experts!
Having the following models.py
class Country(models.Model):
name = models.CharField(max_length=50)
def __unicode__(self):
return self.name
class Meta:
verbose_name = 'Countries Uploaded'
class Users(models.Model):
name = models.CharField(max_length=50)
cUsers = models.ForeignKey(Country)
def __unicode__(self):
return self.name
class Meta:
verbose_name = 'Users on a country'
class GoalsinCountry(models.Model):
Country = models.ForeignKey(VideoTopic)
name = models.CharField(max_length=50)
descr = models.TextField(blank=True, null=True)
def __unicode__(self):
return self.name
class Meta:
verbose_name = 'Goals Topic'
I would like to filter out the users that belongs to a particular country and not all see all users when choosing a country on the combobox, and be able to save this information to a sqlite3 db.
if I add the following code below Country = Models..
gUser = models.ForeignKey(Users)
Using the Django admin interface, will show all users, not filtering users based on the country they are.. Would this be possible to do with Django + Something else? is there any working example/Tutorial - like the northwind MS Tutorial?
Thank you
This is my model
class Category(models.Model):
title = models.ForeignKey(Title, verbose_name="Title")
class Meta:
ordering = ['title']
def __unicode__(self):
return self.title.title
I'm using a form to replace the ForegnKey field by a CharField
class CategoryForm(forms.ModelForm):
title = forms.CharField(label = "Title")
class Meta:
model = Category
class CategoryAdmin(admin.ModelAdmin):
form = CategoryForm
My Title model
class Title(models.Model):
title = models.CharField("Title", max_length=200)
def __unicode__(self):
return self.title
Everything works well when I add and display categories but when I try to edit a category, I get the ForeignKey ID in the title field. I want it to be the title string. Any way to do that ?
Thank you very much
I hadn't check this solution (i can't create test application now) and i don't sure that it works.
Try to add exclude = ("title", ) as CategoryForm member. Also maybe you'll need to override save() (and maybe other) method of CategoryForm.
I have fixed that by making the title unique and adding to_field option to the ForeignKey in my category class. This is the code :
class Title(models.Model):
title = models.CharField("Title", max_length=200, unique=True)
def __unicode__(self):
return self.title
class Category(models.Model):
title = models.ForeignKey(Title, verbose_name="Title", to_field='title')
class Meta:
ordering = ['title']
def __unicode__(self):
return self.title.title
Thank you