Django Multiple Checkbox Generation - python

I am trying to generate a webpage that shows a list of objects pulled from a database with a certain state. The list of objects should include a checkbox next to each object, so that if the user checks the object and presses submit, the server will change the state of that object. Since the list of objects is generated on the fly, I'm confused on how to properly write a Django form that will create the necessary checkboxes.
Any ideas?
Thanks,
Alex

You need a model formset
https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#model-formsets
This will generate a series of forms, one for each item in the queryset you give it.
Assuming the state is saved as a field on the model, you make a custom ModelForm which only has the state field (if it's a BooleanField it'll show as a checkbox by default)
https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#modelform
You can then use this custom form in your model formset:
https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#changing-the-form

Related

Django ForeignKey form field widget

First of all I have tried to research my problem but have not been able to find what I need. My problem might be related to the design of my project (any help would be appreciated).
The problem I am facing is as follows:
I have a few models
I have a model that would be used specifically to create a ModelForm
In this model I have ForeignKey field that is represented by default as a select/option input widget in the ModelForm (for each the value attribute is the ForeignKey and text between the tags is the __str__() of the model the ForeignKey points to. The user sees the __str__() and value attribute of the option tag is submitted which is great).
So far so good but I want to replace the widget with an input text field so I can implement it as a search field.
Now when the user submits the form the string entered in the text input field is submitted and of course django doesn't like that since it expects a foreign key
I already can think of a few solutions to the problem and I am sure I can make it work but each of them feels like I would be violating some best practices. So my question is what should I do?
Do I exclude this particular field from the ModelForm and implement it as an input text field then after form submission make a query with it's value and then store the ForeignKey to the DB
Do I manipulate the data with JavaScript upon submission so that Django receives correct information
Can I clean this fields data with Django and transform it from string to FK?
Am I going the wrong way with this or there is a Django feature for this type of situation?
If anyone has the same problem here is the solution (to my problem at least):
I tried to use the clean_<fieldname> method to change the user entered string to database id. The method wasn't executing because the validation process was stopping earlier because of the difference between the form field and the widget. I redefined the form field to CharField so that step of the validation was working and then the clean_<fieldname> method executes without a problem.

How I can use correctly django ModelChoiceField

I'm a newbie and right now I'm using Django forms to show some fields. One of these fields is a ModelChoiceField this show correctly model data, but I donĀ“t know how I can fill a CharField later of select a option in the ModelChoiceField.
How I can make send the value of option selected for obtain the data that i need for later show this in a CharField, this is possible make directly from a djangoForm or do I need a new view to return the value?
There are two ways to achieve what you want I think:
Provide an initial value for your form value.
Bind your form to some data.
See this related stack overflow to provide initial values.
See Django's documentation on forms for binding data. There are two kinds of form states: bound and unbound. To create a bound form, you just need to create an instance of your form with some data: MyForm({'data-key1': 'data-value1', ...}).

Check box in Django admin run a Python function on save without a BooleanField

Is there a way to have a check box appear in Django admin, but instead of associating it with a BooleanField, having it run a function if it is / is not checked upon save? I don't need to store a Boolean in the database, but may need to store something depending on other fields, and whether the check box was checked.
In particular, I would like to store a ForeignKey if the check box was just checked, empty it (set ForeignKey to null) if the check box was just unchecked, and do nothing it the check box state stayed the same. I don't want to display what this ForeignKey is to the user, just set it or delete it behind the scenes.
You can add any arbitrary fields to a form: they need to be form fields (eg forms.BooleanField) but as long as they don't also exist on the model they won't be saved.
You can then take any action you like in the form's clean() method, or in the modeladmin's save_form method.

Filter a User list using a UserProfile field in Django Admin

I'm trying to filter the User list in Django using a UserProfile Field... I need to implement a queue system where new users are put in a queue until an Admin approves them.
I simply added a is_in_queue boolean field to my UserProfile model... However, when displaying the user list in my Admin area, I realized that you can't filter the list using a Model's foreign key field (in this case, a field of UserProfile)
Apparently, list_display items can be callables but list_filter can't, so I can list IF a user is in the queue without a problem, but the admin would have to scroll through the whole user list to spot which ones are in the queue which makes no sense... Filtering only users that are in the queue (using userprofile.in_queue) would be much more practical...
Finally, I thought about adding a custom view to my admin area that would list only the user in the queue, but that custom view does not show up on the Admin area Index page, and putting together a whole new AdminSite only for a new filtering option seems a bit over the top...
So basically to sum it up: Can I filter my User list based on a
UserProfile field? If not, can I add a custom view that's accessible
from the front page without having to create a completely new
AdminSite only for that?
Django 1.3 fixed that - list_filter now allows to span relations:
https://docs.djangoproject.com/en/1.3/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_filter
You may want to take a look in to using a custom manager for the admin_objects of your model.
class UserAdminManager(models.AdminManager):
"""
Custom manager for the User model.
"""
def get_query_set(self):
"""
Overwrites the get_query_set to only return Users in the queue.
"""
return super(UserAdminManager, self).get_query_set().filter(userprofile__queue=True)
By overwriting the get_query_set method you can filter the results. Then just assign this to the admin_objects property of your User model.
admin_objects = UserAdminManager()
Some of the property names in my example may be wrong, as I don't know your model setup, but hopefully you get the idea.
You can research this further by checking out the django docs and searching for "custom managers".
It sounds to me like the quickest and easiest option is to add a new admin view to your application, specifically for your custom user model. See the Django admin docs for details, though it sounds like you know how to use Admin already.
Once the admin page is specific to your model, all your custom fields will no longer be foreign keys. This would make filtering easy.

Django Formset without instance

In this Django Doc explain how to create a formset that allows you to edit books belonging to a particular author.
What I want to do is: Create a formset that allows you to ADD new book belonging to a NEW author... Add the Book and their Authors in the same formset.
Can you gime a light? thanks.
When you're instantiating the form and formset for the initial display, you don't need to provide an instance - so you will just get blank forms.
When you pass in the data on POST, you can do the form first, save it, and get an instance. Then you can pass that instance into the formset, so that it correctly saves the related objects.
This depends on whether you're doing it yourself, or using the built-in admin.
If you're using the admin, you can use inlines.
If you're doing this in your own application, then it's up to you. Create a single form which has fields for a new author and book. When the user submits the form, it's your job to create the new records.

Categories