Objective: I want to have a ModelChoiceFilter rendered on the page where the options/choices for the user to select are the distinct values of a field in the model.
The app allows users to track the cities that they have visited. I want users to be able to filter the model on country and for the filter options to only be countries that are in the model.
I am using django-filters and do successfully have a MultipleChoiceFilter working where the choices work when hard-coded (either in the models.py or in the FilterForm class:
class cityFilter(django_filters.FilterSet):
continent = MultipleChoiceFilter(
choices=cityModel.continent_choices,
widget=forms.CheckboxSelectMultiple,
label='Continent')
class Meta:
model = cityModel
fields = ['city', 'country', 'continent']
One can also set the choices directly in the FilterSet class like this:
country = MultipleChoiceFilter(
choices=(('GB','United Kingdom'),('FR','France')),
widget=forms.CheckboxSelectMultiple,
label='Country'
)
This works okay for continents but I want to allow a filter for countries. I only want to expose to the user the distinct set of countries in the model (as opposed to hard coding every country).
I could do something like this to get all the distinct countries in the model:
country_choices = cityModel.objects.values('country').distinct()
But I'm not sure where this should be placed in the app to get queried on the page load, and would then need to take each value in the queryset and iterate to turn it into a 'choice' tuple.
Is there a better pattern/approach?
If you want dynamic choices and the choices data from Model, you can try to use queryset in the ModelMultipleChoiceFilter like this:
continent = ModelMultipleChoiceFilter(
queryset=cityModel.objects.values('country').distinct(),
widget=forms.CheckboxSelectMultiple,
label='Continent')
I have model like this:
class Item(models.Model):
number = models.CharField()
menu = models.ForeignKey(Menu)
class Meta:
unique_together = ('number', 'menu')
what I would like to validate is, that 'number' is unique within certain menu, but ignoring case. E.g if ('a1', 1) then don't allow ('A1', 1).
1) I want do this validation on model level, not form.
2) I want store in database values for number EXACTLY as given on input
My first approach was to do it in model's clean method, but there always value of FK field menu is None, so I got RelatedObjectDoesNotExist. Is it issue with Django 1.8 or it was never possible to handle fk fields in models clean?
I noticed that in save method I can acces FK but I can not raise ValidationError which will be handled nice for user.
What is the best strategy to validate it?
See this ticket.
In a nutshell, you can just item.number = value.lower() before saving.
I have a couple models: Phone, Email, Person. I would like to follow a DRY development path, currently I am implementing ModelForms. (Django 1.6)
I need to be able to accept two instances of "Person", the second is optional, and if not present it's associated phone and email forms shouldn't validate. I also would be able to accept multiple phone and email instances, but only require one of each.
Pseudo-Schema
class Person(modelForm):
first_name = CharField
last_name = CharField
...
class Phone(modelForm):
person_ID = ForeignKey(Person)
typ = CharField(choices = ...)
number = CharField
class Email(modelForm):
person_ID = ForeignKey(Person)
typ = CharField(choices = ...)
email = CharField
Pseudo-Form Templete
form>
{{Location_Contact}} #<-required
{{Location_Phone_1}} #<-required
{{Location_Phone_2}} #<-optional but if a field is filled in preform validation
{{Location_Email_1}} #<-required
# optional below but if any part is filled in, treat it like the above
{{Billing_Contact}}
{{Billing_Phone_1}}
{{Billing_Phone_2}}
{{Billing_Email_1}}
/form>
I could probably make this work if I could figure out a way to check and see if a form is untouched and partially filled in; but I haven't found a reliable way of doing this.
I am fairly new to Django maybe going about this the wrong way, any pointers would be appreciated, even if it is a complete overhaul.
You should use Django built-in Formsets module. It was designed specifically to support this and similar use cases.
from django.forms.formsets import formset_factory
PersonFormSet = formset_factory(
PersonForm,
extra=2,
max_num=2,
min_num=1,
validate_min=True
)
extra=2 means that two empty forms will be displayed.
max_num=2 means no more than two forms will ever be displayed (only really makes sense with edit form)
min_num=1 together with validate_min=True means user is required to fill out at least a single form.
Note that validate_min was added in the current dev version and will be avialiable in Django 1.7. In Django up to 1.6 you need to use custom formset validation to achieve the same effect.
I am not sure if my language clear enough but basically I have this form:
class Paper(models.Model):
number = models.CharField(max_length=12,primary_key=True)
project = models.ForeignKey(Project)
class SomeForm(forms.ModelForm):
class Meta:
model = Paper
fields = ('project', 'number')
and django creates a textfield for me. What I want is a select box with the existing primary keys.
Thanks.
I don't think you want a modelform - that's for creating and updating model instances. It sounds like you just want a form to select IDs. Use a normal form, but with a ModelChoiceField.
class SomeForm(forms.Form):
ids = forms.ModelChoiceField(queryset=Paper.objects.all())
You'll need to give the Paper model a __unicode__ method that returns self.number.
This is a problem concerning django.
I have a model say "Automobiles". This will have some basic fields like "Color","Vehicle Owner Name", "Vehicle Cost".
I want to provide a form where the user can add extra fields depending on the automobile that he is adding. For example, if the user is adding a "Car", he will extra fields in the form, dynamically at run time, like "Car Milage", "Cal Manufacturer".
Suppose if the user wants to add a "Truck", he will add "Load that can be carried", "Permit" etc.
How do I achieve this in django?
There are two questions here:
How to provide a form where the user can add new fields at run time?
How to add the fields to the database so that it can be retrieved/queried later?
There are a few approaches:
key/value model (easy, well supported)
JSON data in a TextField (easy, flexible, can't search/index easily)
Dynamic model definition (not so easy, many hidden problems)
It sounds like you want the last one, but I'm not sure it's the best for you. Django is very easy to change/update, if system admins want extra fields, just add them for them and use south to migrate. I don't like generic key/value database schemas, the whole point of a powerful framework like Django is that you can easily write and rewrite custom schemas without resorting to generic approaches.
If you must allow site users/administrators to directly define their data, I'm sure others will show you how to do the first two approaches above. The third approach is what you were asking for, and a bit more crazy, I'll show you how to do. I don't recommend using it in almost all cases, but sometimes it's appropriate.
Dynamic models
Once you know what to do, this is relatively straightforward. You'll need:
1 or 2 models to store the names and types of the fields
(optional) An abstract model to define common functionality for your (subclassed) dynamic models
A function to build (or rebuild) the dynamic model when needed
Code to build or update the database tables when fields are added/removed/renamed
1. Storing the model definition
This is up to you. I imagine you'll have a model CustomCarModel and CustomField to let the user/admin define and store the names and types of the fields you want. You don't have to mirror Django fields directly, you can make your own types that the user may understand better.
Use a forms.ModelForm with inline formsets to let the user build their custom class.
2. Abstract model
Again, this is straightforward, just create a base model with the common fields/methods for all your dynamic models. Make this model abstract.
3. Build a dynamic model
Define a function that takes the required information (maybe an instance of your class from #1) and produces a model class. This is a basic example:
from django.db.models.loading import cache
from django.db import models
def get_custom_car_model(car_model_definition):
""" Create a custom (dynamic) model class based on the given definition.
"""
# What's the name of your app?
_app_label = 'myapp'
# you need to come up with a unique table name
_db_table = 'dynamic_car_%d' % car_model_definition.pk
# you need to come up with a unique model name (used in model caching)
_model_name = "DynamicCar%d" % car_model_definition.pk
# Remove any exist model definition from Django's cache
try:
del cache.app_models[_app_label][_model_name.lower()]
except KeyError:
pass
# We'll build the class attributes here
attrs = {}
# Store a link to the definition for convenience
attrs['car_model_definition'] = car_model_definition
# Create the relevant meta information
class Meta:
app_label = _app_label
db_table = _db_table
managed = False
verbose_name = 'Dynamic Car %s' % car_model_definition
verbose_name_plural = 'Dynamic Cars for %s' % car_model_definition
ordering = ('my_field',)
attrs['__module__'] = 'path.to.your.apps.module'
attrs['Meta'] = Meta
# All of that was just getting the class ready, here is the magic
# Build your model by adding django database Field subclasses to the attrs dict
# What this looks like depends on how you store the users's definitions
# For now, I'll just make them all CharFields
for field in car_model_definition.fields.all():
attrs[field.name] = models.CharField(max_length=50, db_index=True)
# Create the new model class
model_class = type(_model_name, (CustomCarModelBase,), attrs)
return model_class
4. Code to update the database tables
The code above will generate a dynamic model for you, but won't create the database tables. I recommend using South for table manipulation. Here are a couple of functions, which you can connect to pre/post-save signals:
import logging
from south.db import db
from django.db import connection
def create_db_table(model_class):
""" Takes a Django model class and create a database table, if necessary.
"""
table_name = model_class._meta.db_table
if (connection.introspection.table_name_converter(table_name)
not in connection.introspection.table_names()):
fields = [(f.name, f) for f in model_class._meta.fields]
db.create_table(table_name, fields)
logging.debug("Creating table '%s'" % table_name)
def add_necessary_db_columns(model_class):
""" Creates new table or relevant columns as necessary based on the model_class.
No columns or data are renamed or removed.
XXX: May need tweaking if db_column != field.name
"""
# Create table if missing
create_db_table(model_class)
# Add field columns if missing
table_name = model_class._meta.db_table
fields = [(f.column, f) for f in model_class._meta.fields]
db_column_names = [row[0] for row in connection.introspection.get_table_description(connection.cursor(), table_name)]
for column_name, field in fields:
if column_name not in db_column_names:
logging.debug("Adding field '%s' to table '%s'" % (column_name, table_name))
db.add_column(table_name, column_name, field)
And there you have it! You can call get_custom_car_model() to deliver a django model, which you can use to do normal django queries:
CarModel = get_custom_car_model(my_definition)
CarModel.objects.all()
Problems
Your models are hidden from Django until the code creating them is run. You can however run get_custom_car_model for every instance of your definitions in the class_prepared signal for your definition model.
ForeignKeys/ManyToManyFields may not work (I haven't tried)
You will want to use Django's model cache so you don't have to run queries and create the model every time you want to use this. I've left this out above for simplicity
You can get your dynamic models into the admin, but you'll need to dynamically create the admin class as well, and register/reregister/unregister appropriately using signals.
Overview
If you're fine with the added complication and problems, enjoy! One it's running, it works exactly as expected thanks to Django and Python's flexibility. You can feed your model into Django's ModelForm to let the user edit their instances, and perform queries using the database's fields directly. If there is anything you don't understand in the above, you're probably best off not taking this approach (I've intentionally not explained what some of the concepts are for beginners). Keep it Simple!
I really don't think many people need this, but I have used it myself, where we had lots of data in the tables and really, really needed to let the users customise the columns, which changed rarely.
Database
Consider your database design once more.
You should think in terms of how those objects that you want to represent relate to each other in the real world and then try to generalize those relations as much as you can, (so instead of saying each truck has a permit, you say each vehicle has an attribute which can be either a permit, load amount or whatever).
So lets try it:
If you say you have a vehicle and each vehicle can have many user specified attributes consider the following models:
class Attribute(models.Model):
type = models.CharField()
value = models.CharField()
class Vehicle(models.Model):
attribute = models.ManyToMany(Attribute)
As noted before, this is a general idea which enables you to add as much attributes to each vehicle as you want.
If you want specific set of attributes to be available to the user you can use choices in the Attribute.type field.
ATTRIBUTE_CHOICES = (
(1, 'Permit'),
(2, 'Manufacturer'),
)
class Attribute(models.Model):
type = models.CharField(max_length=1, choices=ATTRIBUTE_CHOICES)
value = models.CharField()
Now, perhaps you would want each vehicle sort to have it's own set of available attributes. This can be done by adding yet another model and set foreign key relations from both Vehicle and Attribute models to it.
class VehicleType(models.Model):
name = models.CharField()
class Attribute(models.Model):
vehicle_type = models.ForeigngKey(VehicleType)
type = models.CharField()
value = models.CharField()
class Vehicle(models.Model):
vehicle_type = models.ForeigngKey(VehicleType)
attribute = models.ManyToMany(Attribute)
This way you have a clear picture of how each attribute relates to some vehicle.
Forms
Basically, with this database design, you would require two forms for adding objects into the database. Specifically a model form for a vehicle and a model formset for attributes. You could use jQuery to dynamically add more items on the Attribute formset.
Note
You could also separate Attribute class to AttributeType and AttributeValue so you don't have redundant attribute types stored in your database or if you want to limit the attribute choices for the user but keep the ability to add more types with Django admin site.
To be totally cool, you could use autocomplete on your form to suggest existing attribute types to the user.
Hint: learn more about database normalization.
Other solutions
As suggested in the previous answer by Stuart Marsh
On the other hand you could hard code your models for each vehicle type so that each vehicle type is represented by the subclass of the base vehicle and each subclass can have its own specific attributes but that solutions is not very flexible (if you require flexibility).
You could also keep JSON representation of additional object attributes in one database field but I am not sure this would be helpfull when querying attributes.
Here is my simple test in django shell- I just typed in and it seems work fine-
In [25]: attributes = {
"__module__": "lekhoni.models",
"name": models.CharField(max_length=100),
"address": models.CharField(max_length=100),
}
In [26]: Person = type('Person', (models.Model,), attributes)
In [27]: Person
Out[27]: class 'lekhoni.models.Person'
In [28]: p1= Person()
In [29]: p1.name= 'manir'
In [30]: p1.save()
In [31]: Person.objects.a
Person.objects.aggregate Person.objects.all Person.objects.annotate
In [32]: Person.objects.all()
Out[33]: [Person: Person object]
It seems very simple- not sure why it should not be a considered an option- Reflection is very common is other languages like C# or Java- Anyway I am very new to django things-
Are you talking about in a front end interface, or in the Django admin?
You can't create real fields on the fly like that without a lot of work under the hood. Each model and field in Django has an associated table and column in the database. To add new fields usually requires either raw sql, or migrations using South.
From a front end interface, you could create pseudo fields, and store them in a json format in a single model field.
For example, create an other_data text field in the model. Then allow users to create fields, and store them like {'userfield':'userdata','mileage':54}
But I think if you're using a finite class like vehicles, you would create a base model with the basic vehicle characteristics, and then create models that inherits from the base model for each of the vehicle types.
class base_vehicle(models.Model):
color = models.CharField()
owner_name = models.CharField()
cost = models.DecimalField()
class car(base_vehicle):
mileage = models.IntegerField(default=0)
etc