Django. Add selection flags each list item - django

Good day! I have the object list in admins's cabinet, I must add the flag in front of each item to select (True / False), for example, on this picture
How do I make this with standard methods of Django?
In my case, i have page, for example
I must create checkbox for multichoice and action

You just need to add at least one action. Standard "delete_selected" apparently removed.
class FakeAdmin(admin.ModelAdmin):
actions = ['fake_action']
def fake_action(self, request, queryset):
queryset.update()

Related

Getting False value for a key in self.data even when it is not present in the request

I have 2 radio buttons in the UI, one for setting a variable (ng-model) say selected as true (ng-value=true) and other one for setting it as false (ng-value=false). Now, when none of them is selected it results in the variable selected being absent from the outgoing request (as expected).
However, when that is dealt with Django Forms, the self.data dictionary in the clean() method gives False on accessing self.data.get('selected') / self.data['selected'] why is that so? Shouldn't it be None or at least give a key-error when it was not even present in the actual request?
Note that the variable 'selected' is actually a field in a Django Model with default=False, is that thing responsible for this behaviour? How can I circumvent this situation considering that altering the Django Model field isn't an option?
So I dealt with it the other day by checking for the selected key in the raw request.body. Now, since its a string, I had to parse it to a dict and then access the mentioned key using :
json.loads(request.body).get('selected')
In this way, if selected is not present at all when none of the radio buttons are selected, I get None. Similarly, if the radio button for ng-value=true is selected then I get True and vice-versa.

How to Avoid multi post request by one click?

I have a simple form which adds personal information of a family. sometime it saves two instance of a person just by one submit. Maybe my mouse has problem and and double clicks instead of one click (it has some problems). I think this is not possible and django accepts just one post request from an instance of a form and not more (maybe it accepts). what if may code has problem? if it is problem of my code, why it happens once a while?
house = get_object_or_404(House, id=code)
if request.method == 'POST':
form = ParentForm(request.POST)
if form.is_valid():
# save it if it's valid
parent = form.save(commit=False)
if parent.living == 0:
parent.in_family = 0
if not parent.guardian:
parent.save()
if parent.guardian and parent.in_family:
parent.save()
I use Django 1.8
Edit to clear: this is not the only view sometime saves twice. Maybe it is a bug in django
To solve this problem, first you need to create unique constraint on the corresponding database table. The real solution is based on the database schema. I don't know what fields (columns) you have in the parent table, you can start from add unique constraint to these two fields: child_id and parent_name.
The other problem is you need to prevent the second click. So basically you need to write some JavaScript code: it listens to the onClick event of the submit button. Once the button get clicked, the listener sets the disabled attribute to that button to prevent further clicks.

django and DB modeling: I think I've got Many to Many wrong

I have an object Option which is like a type, it only has a property: name (it could have more properties in the future).
Instances of Option have a unique name.
Many objects may have zero or more of Option instances.
For example:
class Consumer:
options = models.ManyToManyField(Option, blank=True, help_text="the options")
But then, in order to create the Option instances for Consumer's many-to-many options relationship, I need to create a new Option instance and add it to options.
This however "breaks" my uniqueness: Now I have two with the same name! And so forth for every instance of Option I create.for Many-to-Many links. Instead of the 4 I need, I have now 68 in my DB...
I believe I have fundamentally misunderstood Many-To-Many, and / or mis-designed this relationship...
Can anybody help?
EDIT: Here's how I set options in an example:
def enable_option(request, pk=0, option_pk=0, *args, **kwargs):
consumer = get_object_or_404(Consumer, pk=pk)
option = get_object_or_404(Option, pk=option_pk)
new_option = Option()
new_option.name = option.name // I know I am breaking my own rule...but when I read the consumer options, I need the exact same name! Still, I believe I am modeling wrong
new_option.save()
consumer.options.add(new_option)
consumer.save()
return HttpResponse()
I don't really understand why you create a new Option here. You get the existing one; you can just add that to the relationship:
consumer = get_object_or_404(Consumer, pk=pk)
option = get_object_or_404(Option, pk=option_pk)
consumer.options.add(option)
You don't even need to call save, as modifying an m2m does not change the instance itself.

django one widget for two m2m fields

I have two manytomany fields for my model ModelFrom, that both go to the same Model, call it ModelTo.
ModelFrom(models.Model):
field_one = ManyToManyField(ModelTo)
checked = ManyToManyField(ModelTo)
checked is a subset of field one. I have properly validated this in model clean() and adminform clean() methods, and updated model::save() to call self.full_clean().
Ideally, I would have one widget, much like the django.forms.SelectMultiple, but with a checkbox inside each <option>.
what it currently looks like, I have one of these widgets for each field:
:
I want to combine them and have a checkbox or something, here is my unicode representation of what it would look like
{ [ blah: 2 ☐] , [blah: 1 ☑] }
Value in the list -> field one is set. Checked box -> checked is set as it is a subset of field_one.
I have seen jQuery UI MultiSelect Widget but there doesn't seem to be a way to be able to select an option, but not check the box.
I couldn't directly answer my own question, but like most questions, if the answer is not possible then there may be an underlying problem.
Instead of having two many2many fields, I should just have one, setting the through property, for an intermediate field.
Like so:
class IntermediateField(models.Model):
checked = BooleanField()
from = ForeignKey(ModelFrom)
to = ForeignKey(ModelTo)
ModelFrom(models.Model):
field_one = ManyToManyField(ModelTo, through=IntermediateField)
Then, we can just use an inline for IntermediateField in ModelFrom admin, easily checking the boxes etc

django admin actions on all the filtered objects

Admin actions can act on the selected objects in the list page.
Is it possible to act on all the filtered objects?
For example if the admin search for Product names that start with "T-shirt" which results with 400 products and want to increase the price of all of them by 10%.
If the admin can only modify a single page of result at a time it will take a lot of effort.
Thanks
The custom actions are supposed to be used on a group of selected objects, so I don't think there is a standard way of doing what you want.
But I think I have a hack that might work for you... (meaning: use at your own risk and it is untested)
In your action function the request.GET will contain the q parameter used in the admin search. So if you type "T-Shirt" in the search, you should see request.GET look something like:
<QueryDict: {u'q': [u'T-Shirt']}>
You could completely disregard the querystring parameter that your custom action function receives and build your own queryset based on that request.GET's q parameter. Something like:
def increase_price_10_percent(modeladmin, request, queryset):
if request.GET['q'] is None:
# Add some error handling
queryset=Product.objects.filter(name__contains=request.GET['q'])
# Your code to increase price in 10%
increase_price_10_percent.short_description = "Increases price 10% for all products in the search result"
I would make sure to forbid any requests where q is empty. And where you read name__contains you should be mimicking whatever filter you created for the admin of your product object (so, if the search is only looking at the name field, name__contains might suffice; if it looks at the name and description, you would have a more complex filter here in the action function too).
I would also, maybe, add an intermediate page stating what models will be affected and have the user click on "I really know what I'm doing" confirmation button. Look at the code for django.contrib.admin.actions for an example of how to list what objects are being deleted. It should point you in the right direction.
NOTE: the users would still have to select something in the admin page, otherwise the action function would never get called.
This is a more generic solution, is not fully tested(and its pretty naive), so it might break with strange filters. For me works with date filters, foreign key filters, boolean filters.
def publish(modeladmin,request,queryset):
kwargs = {}
for filter,arg in request.GET.items():
kwargs.update({filter:arg})
queryset = queryset.filter(**kwargs)
queryset.update(published=True)