Django - onchange dropdown to display different forms - django

I have a form consisting of 1 dropdown with the following possible values:
cats
dogs
the field haswidget = forms.Select(attrs = {'onchange':'form.submit();'}) And i would like to display a CreateCatsForm or a CreateDogsForm depending on the choice.
I've done some research and i guess i could do it using ajax, as in the example here or is there any usual/good practice way of doing it?

Related

Can you suggest better Django model design? (I'm django beginner)

I'm designing a simple Django model called Clothes. Basically it retrieves what kinds of clothes the user have. I categorized clothes as more than 20 types (such as hoodies, jean, pants) and as big three types: "top", "bottom", "shoes".
In ClothesView, I want to show first 5 clothes for each "top", "bottom", "shoes". And it will retrieve 5 more for individual category if user clicks more (So if user click 'more top', it will return 5 more clothes of 'top' type.
For your better understanding, I wrote the Clothes model conceptually.
class Clothes(models.Model):
id
type = # hoodie, shirts, pants, jean, coat, and so on (more than 20)
big_type = # top, bottom and shoes
owner = ForeignField # some one who post
Expected output (this is just my guess!)
Retrieve 5 clothes for each parent_types ("top", "bottom", "shoes")
user.clothes_set.filter(big_type="top")[:5]
user.clothes_set.filter(big_type="bottom")[:5]
user.clothes_set.filter(big_type="shoes")[:5]
Retrieved 5 more clothes for "top"
user.clothes_set.filter(big_type="top)[5:10]
Retrieve all "hoodies" from my clothes <- this looks ok
user.clothes_set.filter(type="hoodies")
Can you suggest better of efficient model? I may add new Type class and put "through" ... (I'm not sure)
I think you are doing it right. Read here, limiting-queryset.
If you want to query the database in this way. This is the good option instead of retrieving the whole queryset and then slicing it. Through this, the LIMIT for slicing will be issued to the database so, slicing will be done in the database.
On the second opinion, I would advise you to create a new model for Types with the fields type and id.
Then, map it using ManyToMany Relation, if you are not in the case.
For that querying may look like this,
type = Type.objects.get(type="Top").id
clothes = Clothes.objects.filter(type=type)[:5]
Having a different model for Type will help you at the client side rendering.

django form with multiple choice field with potentially infinite choices

I have a model with a many-to-many field that will expand as the user adds more entries for the model. In the form template if I use the conventional {{ form.field }} I get a multiple choice select as is expected, but the problem that will quickly become apparent is when there are 10, 100, 1000 or more choices. What I'd like to provide in the form is a search field where the user can search through all available entries and via AJAX return entries matching their search criteria where they can then select the individual entry choices to be saved in the database.
I'm assuming I will have to manually render the multiple choice form field, but after hours of research I cannot find an example of this anywhere online. Is there an example that exists and I just haven't been able to find? How is one supposed to manually create a form with a multiple choice field in Django? Or am I going about this all wrong?

Django admin: Inline of a Many2Many model with 2 foreign keys

after wracking my brain for days, I just hope someone can point me to the right approach.
I have 4 Models: Page, Element, Style and Post.
Here is my simplyfied models.py/admin.py excerpt: http://pastebin.com/uSHrG0p2
In 2 sentences:
A Element references 1 Style and 1 Post (2 FKs).
A Page can reference many Elements, Elements can be referenced by many pages (M2M).
On the admin site for Page instances I included the M2M relation as 'inline'. So that I have multiple rows to select Element-instances.
One row looking like: [My Post A with My Style X][V]
What I want is to replace that one dropdown with 2 dropdowns. One with all instances of Post and one with all instances of Style (creating Element instances in-place). So that one row would look similar to the Element admin site: [My Post A][V] [My Style X][V]
Sounds easy, but I'm just completely lost after reading and experimenting for 2 days with ModelForms, ModelAdmins, Formsets, ... .
Can I do that without custom views/forms within the Django admin functionality?
One of my approaches was to access the Post/Style instances from a PageAdminForm like this, trying to create a form widget manually from it... but failed to do so:
p = Page.objects.get(pk=1)
f = PageAdminForm(instance=p)
f.base_fields['elements'].choices.queryset[0].post
Any advice or hint which way I need to go?
Thank you for your time!
I got exactly what I wanted after removing the M2M field and linking Elements to a Page with a 3rd ForeignKey in Element:
class Element(models.Model):
page = models.ForeignKey(Page)
post = models.ForeignKey(Post)
style = models.ForeignKey(Style)
Actually a non-M2M link makes more sense for my application after all.
Memo to self: Rethink model relations before trying to outsmart Django :-(

Use CharField choices not only in admin

I've got a model with a property which represents the current status of something.
STATUSES = (('status1', 'The first status'),('status2', 'The second status'),('status3', 'The third status'))
status = models.CharField(choices=STATUSES)
When using Django-Admin, the choices (i.e. "The first status") is displayed instead of the values (i.e "status1"). How can i achieve this when printing out the status in one of my templates? Or is there any better model field to use in this case?
I know I could just use the same string in both elements in the tuples in STATUSES, but this seems like quite bad practice and makes it hard to rename choices if needed.
To display the human readable version of the currently selected choice, use:
{{ instance.get_myfield_display }}
http://docs.djangoproject.com/en/dev/ref/models/instances/#django.db.models.Model.get_FOO_display

Multi-level hierarchy dropdown in django?

I'm looking to categorize my entries, the catch is there are multiple levels of categories I want. An example:
css
layout
floats
specificity, selectors
html
html 5
In this example, css and html are parent categories, css has 2 children and layout has a child of floats.
I suppose the schema I would need would be
class Category:
name = models.TextField()
parentId = models.IntegerField(blank=True)
What I'm clueless on is, how would I be able to make a multi-level dropdown in my admin so that when I post entries I could select a category easily?
So to reiterate, how would I be able to generate a multi-level nested dropdown menu so that when I enter stuff in my Entry model, I can select one category per entry?
It seems that your problem is slightly different from what you are stating. The issue here is not that much about how to display the hierarchy, which is simple:
def __unicode__(self):
return self.depth * " "
The bummer is how to capture and display the hierarchy / depth. This is a common problem: storing trees in realational databases. As usual, your solution depends on tradeoffs between write / read heavy and how much to normalize. You could, for example, on the 'save' method of the model to recursively get to the root and from there store a 'depth' attribute on the nodes. My suggestion is to use django mptt . It is pretty solid and solves much of the normal hurdles. As a bonus, you get a good api for common tree tasks.