i want to directly input in django admin dropdown box - django

This situation is like as above pic.
i want to direct input in dropdown
i mean, I want to make it possible to input directly, including choosing a dropdown.
enter image description here
# models.py
class AccountBook(TimeStampedModel):
branch = models.ForeignKey(Branch, on_delete=models.CASCADE, null=False)
accountclassification = models.ForeignKey(AccountClassification, on_delete=models.CASCADE, null=True)
accountcategory = ChainedForeignKey(
"AccountCategory",
chained_field="accountclassification",
chained_model_field="accountclassification",
show_all=False,
auto_choose=True,
null=True
)
...
# admin.py
#admin.register(AccountBook)
class AccountBookAdmin(admin.ModelAdmin):
list_display = (
"accountclassification",
"accountcategory",
"account_amount",
"account_reference",
"account_manager",
"account_recoder"
)
date_hierarchy = 'created_time'
class Media:
js = (
'smart-selects/admin/js/chainedfk.js',
'smart-selects/admin/js/chainedm2m.js',
)

Related

Should i create one model for multiple apps in a clothing project?

It's my first time creating a project with Django. and it's an e-commerce store for clothing. my confusion now is, most of the items are similar, like women's wears, men's wears, children's wears.Creating different models in different apps means i have to repeat a lot of code because most of the fields will be same and some operations would be more complicated to achieve like global search, etc.
So should i create a single database for all of the items and filter out what i need in different sections like menswear page, women's wear page, etc ?
#For men's model
from django.db import models
from django.urls import reverse
# Create your models here.
CLOTH_CATEGORY_OPTIONS = (
("top", "Top"),
("bottom", "Bottom"),
("complete", "Complete"),
)
CLOTH_GENDER_OPTIONS = (
("male", "Male"),
("female", "Female"),
("unisex", "Unisex"),
)
class Wear(models.Model):
cloth_name = models.CharField(max_length=50, unique=True)
cloth_image = models.CharField(max_length=300)
cloth_category = models.CharField(
max_length=8, choices=CLOTH_CATEGORY_OPTIONS, default='top')
cloth_gender = models.CharField(
max_length=8, choices=CLOTH_GENDER_OPTIONS, default='male')
cloth_price = models.FloatField()
cloth_description = models.TextField()
slug = models.SlugField(default='', editable=False,
max_length=200, null=False)
#For women's model
from django.urls import reverse
# Create your models here.
CLOTH_CATEGORY_OPTIONS = (
("top", "Top"),
("bottom", "Bottom"),
("complete", "Complete"),
)
CLOTH_GENDER_OPTIONS = (
("male", "Male"),
("female", "Female"),
("unisex", "Unisex"),
)
class WomensWear(models.Model):
cloth_name = models.CharField(max_length=50, unique=True)
cloth_image = models.CharField(max_length=300)
cloth_category = models.CharField(
max_length=8, choices=CLOTH_CATEGORY_OPTIONS, default='top')
cloth_gender = models.CharField(
max_length=8, choices=CLOTH_GENDER_OPTIONS, default='male')
cloth_price = models.FloatField()
cloth_description = models.TextField()
slug = models.SlugField(default='', editable=False,
max_length=200, null=False)
As you can see, this is repetitive, so i want to create a global database so i can import it in each app and filter out for men, women, children etc.
You didn't need to repeat all this code for each gender..
Make one model with a field Gender and specify all the genders.
You can filter the clothes in the views with:
Wear.objects.all().filter(Gender=**Male or Women**)
That will filter your products with the gender you give.
Creating 2 models will work for you. A Cloth Model and a Gender Model
One cloth can be of a male or female or both so will work with one to many
class Cloth(models.Model):
gender = models.ForiegnKey(Gender)
....
You will be filtering using:
Cloth.objects.filter(gender__type="male")

django: smart-select ChainedForeignKey / chained dropdown in admin

Hej! :)
I have 5 models which are connected hierarchical with each other.
Section -> division -> group -> class -> wz
one section can have multiple divisions, but one division can only have one section (and so on). Therefor I have ForeignKeys set:
# models.py
class NaceSection(models.Model):
code = models.CharField(max_length=1, unique=True)
description_english = models.CharField(max_length=500)
class NaceDivision(models.Model):
code = models.CharField(max_length=2, unique=True)
nace_section = models.ForeignKey(NaceSection, on_delete=models.CASCADE, related_name="nace_section")
description_english = models.CharField(max_length=500)
class NaceGroup(models.Model):
nace_division = models.ForeignKey(NaceDivision, on_delete=models.CASCADE, related_name="nace_division")
code = models.CharField(max_length=4, unique=True)
description_english = models.CharField(max_length=500)
I than have a model where all those are integrated as M2M fields with a dropdown option.
My goal is to only get the divisions which are in the already selected section in the admin area. (and so on)
I tried smart-select ChainedForeignKey:
# models.py
class Institution(models.Model):
nace_sections = models.ManyToManyField(
NaceSection,
related_name="nace_sections"
)
nace_divisions = ChainedForeignKey(
NaceDivision,
chained_field="nace_sections",
chained_model_field='nace_sections',
blank=True,
)
nace_group = ChainedForeignKey(
NaceGroup,
chained_field="nace_divisions",
chained_model_field='nace_divisions',
blank=True,
)
The organisation and dropdown in the admin area do not change at all and my view with a table of all my results tells me ('42S22', "[42S22] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid column name 'nace_divisions_id'. (207) (SQLExecDirectW)")
With the ChainedManyToManyField nothing at all happens. Does anybody know what's going wrong?
Any help appreciated! :)
nace_sections is specified as models.ManyToManyField in your code
1.Change from ManyToManyField to ForeignKey.
2.Rename chained_model_field values
-->nace_sections to nace_section
-->nace_divisions to nace_division
class Institution(models.Model):
nace_sections = models.ForeignKey(
NaceSection,
related_name="nace_sections"
, on_delete=models.CASCADE
)
nace_divisions = ChainedForeignKey(
NaceDivision,
chained_field="nace_sections",
chained_model_field='nace_section',
blank=True,
)
nace_group = ChainedForeignKey(
NaceGroup,
chained_field="nace_divisions",
chained_model_field='nace_division',
blank=True,
)

get field name from one app to another app in django

We have defined two apps: Manin_matrix and SW_matrix.
We want the field name (project_name) present in class GENERAL_t of models.py file inside Main_matrix app to be inside the models.py file of SW_matrix app.
Basically, project_name_work field in class EDVT of SW_matrix models.py should be the same as project_name of Main_matrix app.
We want this so that in a database for EDVT table we will get the same project id along with the project name.
Main_matrix/models.py
class GENERAL_t(models.Model):
project_name = models.CharField(
blank=True,
null=True,
max_length=40,
verbose_name='Project_Name'
)
platform = models.CharField(
blank=True,
null=True,
max_length=40,
verbose_name='Platform SW'
)
SW_matrix/models.py
class EDVT(models.Model):
project_rel=models.ForeignKey(
GENERAL_t,
null=True,
on_delete=models.SET_NULL,
verbose_name="Choose Project"
)
project_name_work = models.ForeignKey(
GENERAL_t.project_name,
null=True,
verbose_name='Project_Name'
)
You don't need to do that, and a FK won't allow that. The FK field is just the ID of a row in another table, nothing more complex than that really.
When working with ForeignKey links like this it's a good idea to use strings so that you don't have to import the related model. The format of the string is '<appname.ModelName>
For example, I link an object to a (django) content type like this;
source_content_type = models.ForeignKey(
verbose_name=_('source content type'),
to='contenttypes.ContentType',
on_delete=models.CASCADE
)
So to link your EDVT model to a GENERAL_t you'd do;
class EDVT(models.Model):
general_t = models.ForeignKey(
to='Manin_matrix.GENERAL_t',
null=True,
verbose_name='general t'
)
Then if EDVT needs to be able to return a project_name you could do it as a property.
class EDVT(models.Model):
project_rel = models.ForeignKey(
to='Manin_matrix.GENERAL_t',
null=True,
verbose_name='Project_Name'
)
#property
def project_name(self):
return self.project_rel.project_name
Then you can access it either by EDVT.objects.first().project_name or if you didn't implement the property you can do EDVT.objects.first().general_t.project_name (or any other field on that model)

Django Admin custom foreign key select box

I want to customize Django admin select box and show thumbnail in the select box next to the image title
I have a class called Image and another class called News, that has a foreign key to the Image.
Note: I use Django jet as admin template.
class Image(models.Model):
alternate = models.CharField(
verbose_name=_('Alternate'),
max_length=255,
null=True,
blank=True
)
title = models.CharField(
verbose_name=_('Title'),
max_length=255,
null=True,
blank=True
)
artist = models.ManyToManyField(
'Artist',
verbose_name=_('Artist'),
blank=True
)
image = models.ImageField()
def __str__(self):
return "({}) {}".format(self.pk, self.title)
class Meta:
verbose_name = _('Image Attachment')
verbose_name_plural = _('Image Attachments')
#staticmethod
def autocomplete_search_fields():
return 'title',
class News(BaseModel):
title = models.CharField(
verbose_name=_('Title'),
max_length=255,
null=True,
blank=True
)
summery = RichTextField(
verbose_name=_('Summery'),
null=True,
blank=True,
)
main_image = models.ForeignKey(
Image,
verbose_name=_('Main Image'),
on_delete=models.SET_NULL,
null=True,
blank=True,
related_name='images'
)
Now I want to show the thumbnail of the image in choices in Django admin when I want to add news.
Now my select box look like this
You will need to create a custom widget that inherits from Select, the most important part it seems will be setting the option_template_name to be a template that you create to show the image. Since you are using something other than the base Django Admin, you may want to look into extending the widgets in that Library.
Something along the lines of:
class SelectWithImage(Select):
...
option_template_name = 'myapp/forms/widgets/select_option_with_image.html'
...
Then adjust the admin formfield_overrides for the News model in your admin.py as described here and you should be good to go!
This step will look something like this:
from django.contrib import admin
from django.db import models
# Import our custom widget and our model from where they're defined
from myapp.models import News
from myapp.widgets import SelectWithImage
class NewsAdmin(admin.ModelAdmin):
formfield_overrides = {
models.ForeignKey: {'widget': SelectWithImage},
}

Django forms have an "approved" field only available on the admin site and not the view?

I'm learning django and would like to ask a question,
I have a simple form that asks the users for input and click submit, the admin receives an email when a form is submitted. I would like to have the admin approve/deny the form and save it.
I'm struggling with having the approve/deny selection only appears for the admin site. It wither papers for both admin and user or not showing for both.
request_status = (
('select', 'Select'),
('Approved', 'Approved'),
('Denied', 'Denied'),
)
status = models.CharField(max_length=20, choices=request_status, default='select')
My models.py code is:
class SignUp(models.Model):
ENV_CHOICE = (
('select', 'Select'),
('Production', 'Production'),
('Lab', 'Lab'),
('EBC_env', 'EBC_env'),
('Los_Angles', 'Los Angles'),
)
request_status = (
('select', 'Select'),
('Approved', 'Approved'),
('Denied', 'Denied'),
('Added_comment', 'Added_comment'),
)
email = models.EmailField()
full_name = models.CharField(max_length=120, blank=True, null=True)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
what_is_the_change = models.TextField(max_length=250, null=True)
environment = models.CharField(max_length=10, choices=ENV_CHOICE, default='select')
models.DateTimeField(default=timezone.now)
status = models.CharField(max_length=20, choices=request_status, default='select', blank=True)
def __unicode__(self):
return self.email
my forms.py code is:
class SignUpForm(forms.ModelForm):
class Meta:
model = SignUp
fields = ('full_name', 'email', 'environment', 'what_is_the_change', 'change_date_and_time')
It shows model.CharField because my form is inheriting these fields. hopefully I'm making sense otherwise I would not know how to explain it better. Thanks in advance.
In your forms.py assuming that you are using a modelform for your model. Ensure the Meta for the model does not include status in the 'fields'.
e.g.
If your model is ExampleModel in models.py:
class ExampleModel(models.Model):
request_status = (
('select', 'Select'),
('Approved', 'Approved'),
('Denied', 'Denied'),
)
status = models.CharField(max_length=20, choices=request_status, default='select')
user_input = models.CharField(max_length=200)
And your forms.py is:
class ExampleModelForm(forms.ModelForm):
class Meta:
model = ExampleModel
fields = ('user_input',) #note the abscence of status
Should produce a form in admin with both fields, and a form in the user area with only the user input field.