django choice list menu ajax - django

I have this model
CATEGORY_CHOICES = ((1, u'ADSL'),(2, u'HALO-ISDN'),(3, u'IMS') ..... )
class RequestType(models.Model):
rCat = models.IntegerField(max_length=1, choices=CATEGORY_CHOICES, default=ADSL)
rGroup = models.CharField(max_length=32, null=True, blank=True, default='N/A')
rDesc = models.CharField(max_length=64, null=True, blank=True, default='N/A')
rDate = models.DateTimeField(auto_now_add=True)
active = models.BooleanField(default=True)
def __unicode__(self):
return '%s %s %s' `enter code here`% (self.rCat, self.rGroup, self.rDesc)
What I want to do is to create a dynamic form from it.
rCat is used to Create Categories and rGroup is a finer refinement of those categories. What I need is a way to create a drop down choice list from rCat and upon selection of the category to give you a choice to select a Group.
After that I need to validate a form and create a new database entry.
Basically form validation and database entry is simple enough what I have is a problem defining and creating a Ajax function that will dynamically filter the choices.
Any ideas or suggestions?

Related

how to filter data in different models in django?

my models
class Player(TimeStampedModel):
name = models.CharField(max_length=200)
email = models.CharField(max_length=200)
email_verified = models.BooleanField(default=False, blank=True)
phone = models.CharField(max_length=200)
phone_verified = models.BooleanField(default=False, blank=True)
company_id = models.ImageField(upload_to=get_file_path_id_card, null=True,
max_length=255)
company_id_verified = models.BooleanField(default=False, blank=True)
team = models.ForeignKey(Team, related_name='player', on_delete=models.DO_NOTHING)
def __str__(self):
return self.name
this is my model , how to filter data in multiple model?
You can use a Queryset to filter by modal object's field.
You can use this to also filter relationships on models.
In your example, you can do a filter of all the Player entries that have a Character that have Weapon with strength > 10
Player.objects.filter(character__weapon__strength__gt=10)
You can also separate them out into 3 variables for readability purposes.
player_q = Player.objects.filter(character__isnull=False)
ch_q = player_q.filter(weapon__isnull=False)
wpn_dmg = ch_q.filter(strength__gt=10)
Please note that filters are lazy and thus don't return actual model instances untill they're evaluated. I think in this case gt returns an instance.
This documentation goes over all the fieldset lookups you can do with QuerySet object methods filter(), get(), and exclude()

Django Nested Form - Always Showing Object instead of model details

I'm working on a Django project generated via Mezzanine. I've been able to create my models, however I want to have a form where an admin can select from a list to assign a value in a many to many or a one to many relationship. For example, I have a model for Schemas:
class Schema(AutoCreatedUpdatedMixin, SoftDeleteMixin):
"""List of all Schemas in a given database"""
name = models.CharField(max_length=128, null=False)
status = models.BooleanField(max_length=128, null=False, default=True, verbose_name="Is Active")
description = models.CharField(max_length=65535, null=True, blank=True, default=None)
database = models.ForeignKey(Database, on_delete=models.CASCADE)
pull_requests = models.ManyToManyField(Link)
questions = models.ManyToManyField(Question, blank=True)
comments = models.ManyToManyField(Comment, blank=True)
technical_owners = models.ManyToManyField(Employee, related_name='technical_owners_schemas', blank=True)
business_owners = models.ManyToManyField(Employee, related_name='business_owners_schemas', blank=True)
watchers = models.ManyToManyField(Employee, related_name='watchers_schemas', blank=True)
def __unicode__(self):
return "{}".format(self.name)
And I have a model for Employees
class Employee(AutoCreatedUpdatedMixin, SoftDeleteMixin):
"""List of people with any involvement in tables or fields: business or technical owners, developers, etc"""
name = models.CharField(max_length=256, blank=False, null=False, default=None, unique=True)
email = models.EmailField(blank=True, null=True, unique=True)
def __unicode__(self):
return "{}".format(self.employee)
An employee can own multiple schemas and a schema can be owned by multiple employees. My database has an active employee in it, however when I try to create a Schema the employee shows up as Employee Object. Rather I would want the form to show the Employee.name. How can I do this? My admin file contains the following:
class SchemasAdmin(admin.ModelAdmin):
list_display = ['name', 'status', 'database', 'description']
ordering = ['status', 'database', 'name']
actions = []
exclude = ('created_at', 'updated_at', 'deleted_at')
First of all are you using python 2 or 3? For 3, the __str__ method should be used instead of __unicode__. I am writing this because it seems that there's a problem with the __unicode__ method of Employee, which although is defined as:
def __unicode__(self):
return "{}".format(self.employee)
th Employee class does not have an employee attribute (unless there's such an attribute in the mixins that class inherits from (AutoCreatedUpdatedMixin, SoftDeleteMixin) but I don't think that is the case.
In any case, the problem is that you haven't defined a propery __str__ (if using python 3) or __unicode__ (for python 2) method on the Employee class - just define it like:
return self.name
and you should see the employee's name in the django admin select fields.

Django Many to Many Data Duplication?

Background
I'm storing data about researchers. eg, researcher profiles, metrics for each researcher, journals they published in, papers they have, etc.
The Problem
My current database design is this:
Each Researcher has many journals (they published in). The journals have information about it.
Likewise for Subject Areas
But currently, this leads to massive data duplication. Eg, the same journal can appear many times in the Journal table, just linked to a different researcher, etc.
Is there any better way to tackle this problem? Like right now, I have over 5000 rows in the journal column but only about 1000 journals.
Thank you!
EDIT: This is likely due to the way im saving the models for new data (mentioned below). Could anyone provide the proper way to loop and save hashes to models?
Model - Researcher
class Researcher(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
scopus_id = models.BigIntegerField(db_index=True) # Index to make searches quicker
academic_rank = models.CharField(max_length=100)
title = models.CharField(max_length=200,default=None, blank=True, null=True)
salutation = models.CharField(max_length=200,default=None, blank=True, null=True)
scopus_first_name = models.CharField(max_length=100)
scopus_last_name = models.CharField(max_length=100)
affiliation = models.CharField(default=None, blank=True, null=True,max_length = 255)
department = models.CharField(default=None, blank=True, null=True,max_length = 255)
email = models.EmailField(default=None, blank=True, null=True)
properties = JSONField(default=dict)
def __str__(self):
return "{} {}, Scopus ID {}".format(self.scopus_first_name,self.scopus_last_name,self.scopus_id)
Model - Journal
class Journal(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
researchers = models.ManyToManyField(Researcher)
title = models.TextField()
journal_type = models.CharField(max_length=40,default=None,blank=True, null=True)
abbreviation = models.TextField(default=None, blank=True, null=True)
issn = models.CharField(max_length=50, default=None, blank=True, null=True)
journal_rank = models.IntegerField(default=None, blank=True, null=True)
properties = JSONField(default=dict)
def __str__(self):
return self.title
How I'm currently saving them:
db_model_fields = {'abbreviation': 'Front. Artif. Intell. Appl.',
'issn': '09226389',
'journal_type': 'k',
'researchers': <Researcher: x, Scopus ID f>,
'title': 'Frontiers in Artificial Intelligence and Applications'}
# remove researchers or else create will fail (some id need to exist error)
researcher = db_model_fields["researchers"]
del db_model_fields["researchers"]
model_obj = Journal(**db_model_fields)
model_obj.save()
model_obj.researchers.add(researcher)
model_obj.save()
Here is how it works :
class Journal(models.Model):
# some fields
class Researcher(models.Model):
# some fields
journal = models.ManyToManyField(Journal)
Django gonna create a relation table :
Behind the scenes, Django creates an intermediary join table to represent the many-to-many relationship
So you'll have many rows in this table, which is how it works, but journal instance and researcher instance in THEIR table will be unique.
Your error is maybe coming from how you save. Instead of :
model_obj = Journal(**db_model_fields)
model_obj.save()
Try to just do this:
model_obj = Journal.objects.get_or_create(journal_id)
This way you'll get it if it already exists. As none of your fields are unique, you're creating new journal but there's no problem cause django is generating unique ID each time you add a new journal.

I am trying to make a field for a model which is unique for the choices but could be blank or null

I have a field in a model that I would like to be a choice or blank. There may be as many blank items as possible but need to be unique for all others ie there may not be two specials on the same day.
Here is my views.py
class Item(models.Model):
CATEGORY_CHOICES = (('Sandwich', 'Sandwich'), ('Salad', 'Salad'), ('Slider', 'Slider'), ('Side', 'Side'), ('Drink', 'Drink'))
DAYS = (('Monday','Monday'), ('Tuesday','Tuesday'), ('Wednesday','Wednesday'), ('Thursday','Thursday'), ('Friday','Friday'), ('Saturday','Saturday'), ('Sunday','Sunday'))
name = models.CharField(max_length=50)
description = models.TextField()
category = models.CharField(max_length=50)
price = models.DecimalField(max_digits=6, decimal_places=2)
category = models.CharField(max_length=30, choices=CATEGORY_CHOICES)
order = models.PositiveSmallIntegerField(default=0, blank=True, null=True)
special = models.BooleanField(default=False)
day = models.CharField(max_length=30, choices=DAYS, unique=True, blank=True)
publish = models.DateField(auto_now=False, auto_now_add=False),
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
def __str__(self):
return self.name
I am also trying to order the daily specials by day of the week ie (Monday, Tuesday, etc) and I thought the following view was working but it seems to be ordering the Items by id
def specials(request):
specials_list = Item.objects.filter(special = True).order_by('day')
context = {
'specials_list': specials_list,
}
return render(request, 'menu/specials.html', context)
Thanks in advance for the help!
From Django Docs
Unless blank=False is set on the field along with a default then a label containing "---------" will be rendered with the select box. To override this behavior, add a tuple to choices containing None; e.g. (None, 'Your String For Display'). Alternatively, you can use an empty string instead of None where this makes sense - such as on a CharField.
So, for you to allow for a blank choice in any of your tuples, just add the bolded text from the above quote
eg:
CATEGORY_CHOICES = (('Sandwich', 'Sandwich'), ('Salad', 'Salad'), ('Slider', 'Slider'), ('Side', 'Side'), ('Drink', 'Drink'), ('None', 'N/A'))
As for being unique, you already have the days of the week set as unique.

Django form with ManyToMany field

I'm building a simple application using Django where I can record and track information of a set of quality control tests performed regularly to radiotherapy and radiology equipment. It shows a list of all equipment available which I can then select to either perform a set of tests or review other activities performed previously. For now everything seems to be working. I can create new equipments, new tests and filter the tests related to that equipment. But now I'm facing a problem that I can't solve. Here is a sample of my code with the models that I'm struggling:
/models.py
class Test(models.Model):
testgroup = models.ForeignKey(TestGroup)
equipament = models.ManyToManyField(Equipament, blank=True)
number = models.CharField(max_length=10)
name = models.CharField(max_length=120)
description = models.CharField(max_length=300, null=True, blank=True)
frequency = models.ForeignKey(Frequency, null=True, blank=True)
tolerance = models.CharField(max_length=30, null=True, blank=True)
def __str__(self):
return '%s%s%s %s' % (self.testgroup.modality, self.testgroup.abbreviation, self.number, self.name)
pass
class Activity(models.Model):
CONFORMANCE_CHOICES = (
('Yes', 'Yes'),
('No', 'No'),
)
equipament = models.ForeignKey(Equipament, on_delete=models.CASCADE)
type = models.ForeignKey(Type, null=True, blank=True)
date = models.DateField(null=True, blank=True)
summary = models.CharField(max_length=30, null=True, blank=True)
user = models.CharField(max_length=50, null=True, blank=True)
test = models.ManyToManyField(Teste, blank=True)
conformance = models.CharField(max_length=10, choices=CONFORMANCE_CHOICES, null=True, blank=True)
def __str__(self):
return '%s %s' % (self.date, self.equipament)
pass
What I need to do is to be able to save a result, one of the conformance choices to each test. I am able to display in the Activity view a list of the tests I want to perform but how can I save that conformance field for each test? My best approach was to change the conformance field to a ManyToManyField and through the form create the relations between Tests and Conformance but I get for each test all the conformance choices. How can I define just one conformance choice (the selected one) to one test? Please help...
I was able to work this out. I am posting my solution. Maybe someone had or will have the same problem. To perform what I wanted I used inlinefomset_factory creating an intermediary model called Results with a ForeignKey to Activity. Everything works now.