Modelchoicefield Queryset Confusion - django

All,
I'm new to Django and have been doing pretty good so far but this one has me stumped. I'm trying to utilize ModelChoiceField for a number of records that have the same name. I'm using Postgresql so I was able to determine that I need to use the distinct command and that is working perfectly. The records in my dropdown are all stripped down to just one version of each of the records. However, when I try to get all of the versions of a particular record, that's where I'm getting lost. I am able to get the detail of each record if I don't use distinct via a DetailView, but I am really trying to get all versions of each record on the screen after the modelchoicefield.
Here is my form:
class History(forms.Form):
dropdown = forms.ModelChoiceField(queryset=History.objects.all())
def __init__(self, user, *args, **kwargs):
super(History, self).__init__(*args, **kwargs)
self.fields['dropdown'].widget.attrs['class'] = 'choices1'
self.fields['dropdown'].empty_label = ''
qs = History.objects.all().distinct('record_name')
self.fields['dropdown'].queryset = qs
I am ultimately trying to get a view the queryset on the screen via my template. I have tried several different versions of code in the template but nothing seems to work. If I use the CBV DetailView without distinct I can get all of the records with their detail view fine. However, that's not what I'm trying to do. I have played with several versions of the queryset command in the template as I found several questions similar to mine but can't seem to get it to work. I found a couple of references to something similar to:
{% for record in form.history.field.queryset %}
etc.
{% endfor %}
But can't seem to get it to work in my Django template. Any and all help is appreciated! Thank you in advance!

In this case I'd either suggest
a) to put the value of your dropdown field into your url matching. See the django docs for named groups in URL. Additionally, you could add an onchange event to your dropdown-field which redirects to <current url>/<value of dropdown> or simply change the value of (if existing) buttons which links to the following page. Caution: With this solution you must ensure that the values of your dropdown field matches url-format (django's slugify might be useful for this).
or
b) to add your dropdown field to your input form or as input field. Then you can extract the value of your dropdown with:
try:
dropdown_value = request.POST['dropdown-field-name'] # dict-error if field is not in request.POST
except:
# some error actions
then you can add this value as filter to your queryset:
def get_queryset(self, dropdown_value=None):
# ...
qs = qs.filter('field-name' = dropdown_value) # possibly no/wrong results if dropdown_value is corrupted or manipulated

Related

In Django admin, how can I filter a MultipleChoiceField depending on a previous MultipleChoiceField?

In my django website, I have 3 classes: Thing, Category and SubCategory.
Thing has 2 ForeignKeys: "Category" and "SubCategory" (such as Car and Ferrari).
SubCategory has 1 ForeighKey: "Category" (Ferrari is in the category Car)
When I create an instance of Thing in the Admin part and when I choose a Category, I would like that the "SubCategory" field only shows the SubCategories linked to the Category I chose. Is that possible?
I saw the possibility to change the AdminForm like:
class ThingFormAdmin(forms.ModelForm):
def __init__(self,Category,*args,**kwargs):
super (ThingFormAdmin,self ).__init__(*args,**kwargs) # populates the post
self.fields['sub_category'].queryset = SubCategory.objects.filter(category= ... )
But I don't know what to write on the ...
Thanks for the help!
in general always this solution would work:
you need some javascript to catch what has been selected for first selection. then do filtering agin using javascript.
but in django admin, there is autocomplete_fields available. using this would create a kind of selection-input that uses ajax to do some magic filtering on choices when user types some characters. it uses the get_search_results method of the related models admin.ModelAdmin class. overriding that method and giving some extra data to that method could help. but it's the longest way to walk.
Thanks! I will look in the 1st answer after the 2nd, because the fact that I don't have to write JS is very nice, as I am very bad in it.
I manage to use the autocomplete_field to work, but I am stuck with the redefinition of the get_search_results method. If I understood correctly the doc, it will be something like:
def get_search_results(self, request, queryset, search_term):
queryset, use_distinct = super().get_search_results(request, queryset, search_term)
try:
cat = search_term
except ValueError:
queryset |= self.model.objects.all()
else:
queryset |= self.model.objects.filter(category=cat)
return queryset, use_distinct
But I don't understand from where this search_term comes from, and how I can specify it. Any ideas?
https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html
This tutorial will walk you through every step of doing whatever I presume you need to do.

How do I get django template to recognize manytomanyfield comparison?

In my project, I am currently trying to access a manytomany field and compare it to another. I have several cases where I am doing something similar and it is working . The difference in this case is that I am trying to essentially say if one of the values in this many to many field equals a value in this other manytomanyfield, then do something....
Here is my code...
Book(models.Model):
publisher = models.ManyToManyField(Name)
Userprofile(models.Model):
publisher = models.ManyToManyField(Name)
In my Django template I am trying to do something like...
{% If user_publisher in form.initial.publisher_set.all %}
{{ publisher.name }}
{% endif %}
The example above is a simplified version of what I'm trying to do....I'm essentially trying to compare the manytomany fields and if any of the values match, perform an action. I've been at this most of today and have tried several combinations.
If I do something like
{% if user in form.initial.publisher.all %}
This works fine. I'm struggling to try and figure out how I can compare manytomanyfields. I suspect the user query works fine because it's not a manytomanyfield.
I'm thinking my format is off. I have tried to use the _set to publisher and the user publisher and when I go so far as to print the output, I am actually seeing that both the user_publisher and publisher querysets are the same. However, my django template is not showing me any results. Thanks in advance for any thoughts.
I have surfed SO all afternoon as well as Google, but can't quite figure out what I'm doing wrong.
Here is more detail to my issue. I am currently doing a CreateView whereby I am trying to get an existing record by overriding get_initial as shown below:
class BookUpdateView(CreateView):
model = Book
form_class = Book
template_name = 'Book/update_book.html'
def get_initial(self):
initial = super(BookUpdateView, self).get_initial()
book = Book.objects.get(pk=self.kwargs["pk"])
initial = book.__dict__.copy()
initial.update({
"publisher": publisher.all(),
})
return initial
Because I am copying in these records as a starting point and this is a CreateView, I don't yet have a PK or ID to query from a get_context_data perspective. Not sure how to go about getting the data that I am copying in but have not yet saved. I am actually trying to figure out if a user has the same publisher via their user profile and was able to figure out the format for get_context_data as shown below:
def get_context_data(self, **kwargs):
context = super(BookUpdateView, self).get_context_data(**kwargs)
user_publisher = self.request.user.userprofile.publisher.all()
return context
I tried to do something like....
{% if user_publisher in form.initial.publisher_set.all %}
But the template never recognizes that these two in fact do match...
When I print the variables....
They both show...
<QuerySet [<Publisher: ACME Publishing>]>
<QuerySet [<Publisher: ACME Publishing>]>
But the template does not recognize that they are the same. The screen is not rendered as I would expect when using the template language above. No errors, but end result isn't what I would expect either. Thanks in advance for any additional thoughts.
After a day or two of thinking about this, was able to figure out how to grab the PK and then use it in the context so that I could leverage the information via the context and not the form directly.
def get_context_data(self, **kwargs):
context = super(UpdateProcedureView, self).get_context_data(**kwargs)
pk=self.kwargs["pk"]
publisher = Publisher.objects.filter(pk=pk).filter(individual_access=self.request.user).count()
return context
Then in the form I can say something like if publisher > 0 then do something fancy. Thanks for the suggestions along the way to help me think this through.

Query Database Table Without Using Foreign Key Django Postgresql

I am trying to query a table where I have many records with the same name, on purpose. In my example, I'm using the make of the car, and unfortunately I've already ruled out using a foreignkey. Long story. Anyway, I've been able to determine that I can query the table using a ModelChoiceField and using the distinct command as I'm using Postgresql as shown below:
class Vehicle(forms.Form):
dropdown = forms.ModelChoiceField(queryset=Car.objects.none())
def __init__(self, *args, **kwargs):
super(Vehicle, self).__init__(*args, **kwargs)
self.fields['dropdown'].empty_label = ''
qs = Car.objects.distinct('vehicle_make')
The code above does what I need related to the dropdown, it limits the ModelChoiceField to just the unique values of the vehicle_make of the car.
The challenge is when I go to try to display all of the records with that vehicle_make in my template. I've tried to do a Detail View, but it is only showing me that individual record. That make sense since detail view is just for that record, but I'm trying to figure out how to query the table to show me all of the records with that vehicle_make. I've explored the ChoiceField as well, but can't seem to get this to work either. I've tried several variations of the code below in the template, but nothing seems to work.
{% for vehicle_make in car.queryset %}
{{ vehicle_make }}
{% endfor %}
My model is as follows:
Car(models.Model):
vehicle_make = models.Charfield(max_length=264,unique=False)
def __str__(self):
return self.vehicle_make
Thanks in advance for your input and suggestions.
You can query for all Car objects with a given value for vehicle_make with Car.objects.filter(vehicle_make = 'foo'). For example, this ListView would list all cars:
from django.views.generic.list import ListView
from .models import Car
class CarListView(ListView):
context_object_name = "car_list"
queryset = Car.objects.all()
Whereas this view would list all cars of make 'foo':
class FooCarListView(ListView):
context_object_name = "car_list"
queryset = Car.objects.filter(vehicle_make = 'foo')
One easy way to make this more "dynamic" would be to look for a search query in the url, either as a keyword argument or as a querystring. You could use your existing form to create a URL like this, then parse it in a view. For instance, this view would look for URLs appended with ?search=bar:
class SearchableCarListView(ListView):
context_object_name = "car_list"
def get_queryset(self):
search_term = self.request.GET.get('search', None)
if search_term is not None:
return Car.objects.filter(vehicle_make = search_term)
return Car.objects.all()
Your use case may be better served by using an icontains or iexact lookup, or even by making use of Django's full text search.
In the template for any of these views, you can access all of the Car objects in your queryset like so:
{% for car in car_list %}
{{car}}
{% endfor %}
I hope that I have understood and addressed your question. I am not 100% sure how you are using your form right now, so please let me know if I have overlooked anything there.
After our discussion in the comments, I think you are overcomplicating things with your form, and I think that your lookup might not be doing what you want.
We will get a ValuesQuerySet of all distinct vehicle_make values:
qs = Car.objects.values('vehicle_make').distinct()
(See: Select DISTINCT individual columns in django?)
This returns a ValuesQuerySet that looks like this:
<QuerySet [{'vehicle_make': 'vehicle_make_1'}, {'vehicle_make': 'vehicle_make_2'}...]
Where vehicle_make_1, vehicle_make_2 etc. are your distinct values.
We can give this queryset qs to our template and construct a select element. We could also simplify it first to a list of values to make it easier to work with in the template:
values_list = [ c['vehicle_make'] for c in qs.all() ]
Pass that value to our template and use it to make our select element:
<select name='search'>
{% for vehicle_make in values_list %}
<option value = {{vehicle_make}} > {{vehicle_make}} </option>
{% endfor %}
</select>
From here you have several options. In my opinion, the simplest thing would be using this select element in a form that uses the GET method to construct a search URL like we discussed earlier. Check out the first answer to this question for more info: <form method="link" > or <a>? What's the difference? There is a code snippet in the first answer to that question that can easily be adapted to create a GET-based search form with your newly-created select element.

Create a form in Django with hundreds of check boxes without hitting the URL length limit in IE8

I have a form that needs to have hundreds of check boxes, but if a user selects all of them the resulting URL is so long that IE8 truncates it at about 2000 characters.
The current implementation creates URLs like:
http://example.com?c_$id1=on&c_$id2=on&c$id3=on...etc.
Basically, every check box has an ID, and that ID is sent as a parameter to the URL.
I want to change the URLs to be like this instead, with pipe-separated values:
http://example.com?c=$id1|$id2|$id3|$id4...etc.
Client-side, this is easy because I already submit the form with JavaScript, but server-side I want to avoid doing too much crazy work in my Django form, which currently has these checkboxes constructed as a couple hundred BooleanFields.
What's the best way to reverse the pipe-separated values in the Django form so it works smoothly?
Couple other notes:
I can't change the parameters to be any shorter.
I can't just send a post request, I need the URLs to be bookmarkable.
I can't get rid of the IE8 users...yet.
I found a solution yesterday after posting. It's somewhat lame, but from the user's perspective everything seems to work well.
Add a field to the form for c, and set it to have a hidden widget:
c = forms.CharField(required=False, widget=forms.HiddenInput())
Add the hundreds of checkboxes to the form in its init method using a loop and a DB query:
def __init__(self, *args, **kwargs):
super(SearchForm, self).__init__(*args, **kwargs)
COURTS = Court.objects.filter(in_use=True).values_list('courtUUID', 'short_name')
for court in COURTS:
self.fields['court_' + court[0]] = forms.BooleanField(
label=court[1],
required=False,
initial=True,
widget=forms.CheckboxInput(attrs={'checked': 'checked'})
)
Pull the two together by converting the value of the c field back into the checkboxes in the clean method:
def clean(self):
# Convert the value in the court field to the various court_* fields
court_str = cleaned_data.get('c')
if court_str:
court_ids = court_str.split(' ') # Using a pipe here will suck on IE and Chrome (but not FF)
for id in court_ids:
cleaned_data['court_%s' % id] = True
In your template show the checkboxes to your users, but use JavaScript to populate the hidden field (c) in your GET parameters.
This solution seems to be working on our live site and has the nice advantage of working even if the user doesn't have javascript enabled or if the use an old URL (the old checkboxes still work).
The part I hate about this is that I'm hacking the heck out of the Django form, and it's a bit of an injustice to them. Happy to hear a better solution though.

Limiting Django ModelChoiceField queryset to selected items

Here is what I've been struggling for a day...
I have a Message model in which recipients is a ManyToManyField to the User model.
Then there is a form for composing messages. As there are thousands of users, it is not convenient to display the options in a multiple select widget in the form, which is the default behavior. Instead, using FcbkComplete jquery plugin, I made the recipients field look like an input field where the user types the recipients, and it WORKS.
But...
Although not visible on the form page, all the user list is rendered into the page in the select field, which is something I don't want for obvious reasons.
I tried overriding the ModelChoiceField's behavior manipulating validation and queryset, I played with the MultipleChoice widget, etc. But none of them worked and felt natural.
So, what is the (best) way to avoid having the whole list of options on the client side, but still be able to validate against a queryset?
Have you seen django-ajax-selects? I've never used it, but it's in my mental grab bag for when I come across a problem like what it sounds like you're trying to solve...
I would be trying one of two ways (both of which might be bad! I'm really just thinking out aloud here):
Setting the field's queryset to be empty (queryset = Model.objects.none()) and having the jquery tool use ajax views for selecting/searching users. Use a clean_field function to manually validate the users are valid.
This would be my preferred choice: edit the template to not loop through the field's queryset - so the html would have 0 options inside the select tags. That is, not using form.as_p() method or anything.
One thing I'm not sure about is whether #2 would still hit the database, pulling out the 5k+ objects, just not displaying them in the html. I don't think it should, but... not sure, at all!
If you don't care about suggestions, and is OK to use the ID, Django Admin comes with a raw_id_field attribute for these situations.
You could also make a widget, that uses the username instead of the ID and returns a valid user. Something among the lines of:
# I haven't tested this code. It's just for illustration purposes
class RawUsernameField(forms.CharField):
def clean(self, value):
try:
return User.objects.get(username=value)
except User.DoesNotExist:
rause forms.ValidationError(u'Invalid Username')
I solve this by overriding the forms.ModelMultipleChoiceField's default widget. The new widget returns only the selected fields, not the entire list of options:
class SelectMultipleUserWidget(forms.SelectMultiple):
def render_options(self, choices, selected_choices):
choices = [c for c in self.choices if str(c[0]) in selected_choices]
self.choices = choices
return super(SelectMultipleUserWidget,
self).render_options([], selected_choices)
class ComposeForm(forms.Form):
recipients = forms.ModelMultipleChoiceField(queryset=User.objects.all(),
widget=SelectMultipleUserWidget)
...