How to pass dynamic filtering options in django_filters form instead of all model objects? - django

I have the following structure of the project (models):
Company (based on Groups) <-- Products (foreignKey to Company) <-- Reviews (foreignKey to Products).
Inside template i want to give a user an opportunity to filter reviews by products, but when using django_filters it shows corrects queryset of reviews (related only to company's products) but in filter form dropdown options i can see all products of all companies (even those which are not presented on the page), for example for Company X i see on my page only Cactus and Dakimakura reviews, but in filter form i can select Sausage (but i shouldnt, because its product from another company).
For now it's all looks like this:
#View
def reviewsView(request):
context = {}
user = request.user
company = user.company
products_qset = ProductModel.objects.filter(company=company)
reviews_objects = ReviewModel.objects.filter(product__in=products_qset)
filter = ReviewFilter(request.GET, queryset=reviews_objects)
context['filter'] = filter
return render(request, 'companies/reviews.html', context)
#Filter
class ReviewFilter(django_filters.FilterSet):
class Meta:
model = ReviewModel
fields = [
'product',
'marketplace',
'operator',
'state'
]
#Template
<form action="" method="get">
{{ filter.form.as_p }}
<input type="submit" name="press me" id="">
</form>
<div class="review-list">
{% for i in filter %}
{{i.product}}, {{i.marketplace}} etc.
{% endfor %}
I've done quite a lot of research on django_filters docs and this question seems like duplicate, but i can't fully understand what and why is happening to init in this answer and how to correctly rewrike class ReviewFilter so filter instance would do something like this (in View):
filter = ReviewFilter(request.GET, queryset_to_dispplay=MyQueryset, queryset_to_display_filtering_options=MyQueryset). For now its surely happening because ReviewFilter Meta points to the all table (ReviewModel) objects, instead of filtered beforehands.
I also trying to apply pagination on this page (i cut this from question code for "shortness") and after i will be able to implement filtering i would like to merge those two somehow, but if what i want is not possible - please point me to the right direction (for example: 'you can do this by writing your very own filtering system using some js, no need to use django_filters' or 'with angular.js/view.js/somethingelse you can have it all from the box').

Related

How do I add non-field related date range to Django admin form

I have a django admin page which is for viewing purposes only and rather than displaying data from the model, it is displaying data for a table linked by a foreignkey to an intermediate table which is linked via a foreign key to my model. I want to apply a date range filter on the third table.
class Brand(models.Model):
data ...
class Organisation (models.Model):
data ...
brand = models.ForeignKey(Brand, on_delete=models.CASCADE)
class DailyStat (models.Model):
stat_type = model.CharField(max_lenth=11, choices=STAT_TYPE_CHOICES
date = models.DateField()
organisation = models.ForeignKey(Organisation, on_delete=models.CASCADE)
I then created a change_form.html template in 'templates/admin/brand' which displays the data from DailyStat which I want for the Brand.
But I want to be able to filter this so I created a new form
class BrandAdminForm(forms.ModelForm):
from_date = forms.DateField(widget=admin.widgets.AdminDateWidget())
to_date = forms.DateField(widget=admin.widgets.AdminDateWidget())
class Meta:
model = Brand
fields = ['id','from_date','to_date']
And within the BrandAdmin definition, referenced it
class BrandAdmin(admin.ModelAdmin):
list_display = ['name','get_page_views','cqc_brand_id']
ordering = ['name']
search_fields = ['name']
form = BrandAdminForm
These fields didn't automatically show in the detail page so I added the following within the form tags of {% block content %} of the change_form.html
<table style="width:60%">
<tr>
<td>From: </td>
<td>{{ adminform.form.from_date }}</td>
<td rowspan=2><button type="submit" value="Save and continue editing" class="btn viewsitelink">Filter</button></td>
</tr>
<tr>
<td>To: </td>
<td>{{ adminform.form.to_date }}</td>
</tr>
</table>
So the fields now show in the form (I haven't written the processing to use the fields yet) BUT, I am running django-cms and when I click the filter button, it isn't returning to the pages under the django-cms admin panel rather than returning to the admin view.
If there is a better approach, how can I get to filtering the data I require more effectively OR what am I doing wrong that it isn't returning to the correct view (the form tag shows action="")
Thanks
This is definitely doable, but there are a few things you should consider:
This isn't really what a change-view is meant for. It feels weird from a UX perspective to have (on a page which is essentially one big form) form-elements unrelated to the form you are submitting.
django admin is not meant to be a user-facing production ready environment. If you're trying to make it do things it's not easy to do, it's normally a good sign you should be making your own views here.
The problem with your approach
The modelAdmin.form attribute, is meant to be a form which displays data from an instance of the relevant model, and which saves the returned POST data back to that same instance.
It isn't the form the view actually uses in the end. It is the form django-admin uses to build the form that is finally used though. The admin app does quite a bit of processing along the way, based off attributes that are set on modelAdmin so adding (unrelated) fields to modelAdmin.form won't necessarily correspond to fields on the finally rendered form.
If you want to add in to_date and from_date it should be done in a separate form. (For one thing, you otherwise wouldn't be able to change the dates without submitting your whole form).
Solution
You are far better to add a separate form, and use GET query parameters to update your dates. Something like this:
class DateForm(forms.Form):
from_date = forms.DateField(widget=admin.widgets.AdminDateWidget())
to_date = forms.DateField(widget=admin.widgets.AdminDateWidget())
class BrandAdmin(admin.ModelAdmin):
...
def change_view(self, request, object_id, form_url="", extra_context=None):
date_form = DateForm(request.GET)
if extra_context is None:
extra_context = {}
extra_context['date_form'] = date_form
return super().change_view(
request, object_id, form_url="", extra_context=extra_context
)
Then in your change_form template
{% block content %}
<form method="get">
{{date_form}}
<input type="submit" value="Update dates">
</form>
{{ block.super }}
{% endblock %}
You will now have access to to_date and from_date in your template where you list your via request.GET and you should then be able to filter using them.

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.

Django - Checkboxes & ManytoMany relationships in TemplateView

I have a app where users can register their company and then select a number of settings from a list. Both the company and services are different models.
class Company(models.Model):
name = models.CharField(max_length=100)
(...)
class Service(models.Model):
name = models.CharField(max_length=100)
linked_companies = ManyToManyField(Company, blank=True)
What I want is to have a large list of services, with checkboxes behind their names, so the owner can quickly select the services that he wants to connect to his model. This used to be done through the admin interface, but due popular demand this feature is moved to 'the front'.
The problem is that I do not know how to fit this into the traditional (generic) view/form combinations that we' ve been using so far, since two different models are involved.
I am trying a more custom solution, but have hit a wall and I am wondering if you could help me. I have created a html page that should display both the list of services and a 'save' button.
<form action="." method="POST" class="post-form">{% csrf_token %}
<ul>
{% recursetree services %}
<li>
<label><input type="checkbox" name='service' value={{ node.pk }}><h3>{{ node.name }}</h3></label>
{% if not node.is_leaf_node %}
<ul class="children">
{{ children }}
</ul>
{% endif %}
</li>
{% endrecursetree %}
</ul>
<button type="submit" class="save btn btn-default">Add Selected
</button>
</form>
I am using the following ModelForm:
class FacetForm(forms.ModelForm):
class Meta:
model = Services
fields = ['linked_tenants', 'name']
widgets = {
'linked_tenants' : CheckboxSelectMultiple()
}
This HTML page seems to work as intended, showing a long list of services with checkboxes after their names.
However, I have trouble creating a function view. Together with a collegue the following view was created
class FacetList(TenantRootedMixin, TemplateView):
def get_context_data(self, **kwargs):
d = super(ServiceList, self).get_context_data(**kwargs)
d['services'] = Services.objects.all()
d['current_company'] = self.context.company.id
return d
def form_valid(self, *args, **kwargs):
return super(ServiceList, self).form_valid(*args, **kwargs)
This view works in the sense that it shows all of the relevant information (with the checkboxes). If I change the query to filter the services by 'company id'. the view works as desired as well.
The problems I have revolve around the fact that pressing 'save'. crashes the program, throwing the following error.
'super' object has no attribute 'post'
Our program works mostly through generic classbased views and modelforms, so we have relativly limited experience with creating our own custom solutions. By my own estimation the problem seems to be twofold:
The view is probably not configured right to process the 'post' data
It is questionable if the data will be processed to the database afterwards.
Though are 'sollution' is currently flawed, are we looking in the right direction? Are we on the right way to solve our problem?
Regards
I believe you are on the right track. What I would suggest is to not be afraid to move away from generic views and move toward a more custom solution (even if you are inexperienced with it.)
The first routine that comes to my mind would be as follows:
gather all the id's that were checked by the user into a list from request.POST
Update the appropriate object's M2M field to contain these new id's.
Save the fore-mentioned object.
[Edit]
One thing I have trouble with is gathering the ID' s from the request.POST. Could you provide me with an example on how to do this?
Sure, from your HTML file I see you are creating inputs with name=service. That leads me to believe you could do something like:
ids = request.POST.get('service')
but to teach you how to fish rather than giving you a fish, you should try to simply:
print request.POST.items()
This will return and print to the console everything that was posted from your form to your view function. Use this to find out if you are getting a list of id's from the template to the server. If not, you may have to re-evaluate how you are building your form in your template.
Your first point is correct: TemplateView has no "post" method defined and that is why you get the error message when you call super().form_valid. You must either define it yourself or use a CBV which has a post method that you can override (e.g. UpdateView)
And I also believe that your second point is correct.
You would need to use an UpdateView to use the built in functionality (or CreateView).
I had a similar problem to solve (selecting values from many-to-many fields in the front-end) and I ended up with doing it "by hand" because I could not get it to work with CBV. "by-hand" => parse the values from the form, update the database, return HttpResponse
You might want to look at ModelFormSets:
https://docs.djangoproject.com/en/1.11/topics/forms/modelforms/#model-formsets
Hope this helps!
Alex

Can I create multiple model instances with CreateView?

I have a form whose purpose is to let a user add, edit, subtract and reorder songs. JavaScript DOM manipulation lets users add, subtract and reorder songs fields. The reordering is via jQuery UI's sortable interaction. The order of songs is crucial.
HTML field name attribute values are duplicated. I'm not using Django to generate the form.
Assuming there are two songs on submission, Firebug shows the form DOM looking something like this (csrf omitted):
<form method="post" action="/save/">
<ul id="sortable_songs" class="ui-sortable">
<li>
<input type="text" name="title" id="song_txt_1">
<textarea id="more_info_txtarea_1" name="more_info"></textarea>
</li>
<li>
<input type="text" name="title" id="song_txt_2">
<textarea id="more_info_txtarea_2" name="more_info"></textarea>
</li>
</ul>
<button type="submit">save</button>
</form>
Example query string:
title=FOO&more_info=FOO+INFO&title=BAR&more_info=BAR+INFO
The model:
class Song(models.Model):
title = models.CharField(max_length=65)
more_info = models.CharField(max_length=255)
#todo: foreignkey to User
Probably not much data is involved, both in each record and with regard to the number of records per user. Hence I'm assuming it makes sense that, for a given user, when the form is submitted I'll delete all of their song instances in the Song table and create a bunch of new ones according to the form. (As opposed to having to edit existing records and having a db field which indicates song order).
It seems like I shouldn't write my own view so I'm trying Django's generic CreateView, but perhaps unsurprisingly, with the above user input only a model instance with "BAR" and "BAR INFO" is created -no "FOO" instance is made.
Is there a simple way around this?
You should use Formsets, in this way you can manage multiple instances of an object in a simple way, however you need to control some extra variables and format your query string. But all is covered in the documentation.
You will need a order field in your model:
class Song(models.Model):
title = models.CharField(max_length=65)
more_info = models.CharField(max_length=255)
#todo: foreignkey to User
order = models.PositiveIntegerField()
class Meta:
order_by = ['order']
# to ensure database integrity
unique_thogeter = [(user, order)]
you may also need to update your create view,
class SongListCreate(CreateView):
model = Song
def get_context_data(self, *args, **kwargs):
context = super(SongListCreate, self).get_context_data(*args, **kwargs)
# add a song formset to the context
# or a bound formset from validation
return context
def form_valid(self, form):
formset = SongFormset(#post data)
objects = formset.save(commit = False)
objects.update(#user instance,
#and other data you might need like the new orders)
objects.save()
return super(SongListCreate, self).form_valid(form)
This is roughly what you may need to do, working with formsets is quite a bit hard while you get used to.
You may also want to use a custom library to manage the order of the songs easily, like moving up or down, something like django-positions.
Regards.

How to write view from ModelChoiceField response?

I'm new to Django forms and am getting hung up on something that seems like it should be very simple.
I want to create a dropdown selector that directs users to detail pages, one for each year.
In models.py I have:
class Season(models.Model):
year = models.IntegerField(unique = True, max_length=4, verbose_name = "Season (year)")
…
class season_choice(forms.Form):
choice = forms.ModelChoiceField(queryset=Season.objects.all().order_by('year'), empty_label="Season")
class Meta:
model = Season
In my template:
<form action="/season_detail/{{ choice.year }}" method="get">
{{ season_choice.as_p }}
<input type="submit" value="Go" />
</form>
The dropdown selector shows up fine, producing choices formatted like so:
<select id="id_choice" name="choice">
<option selected="selected" value="">Season</option>
<option value="1">1981</option>
<option value="2">1982</option>
<option value="3">1983</option>
…
Choosing and submitting a year, for instance 1983, now takes me to /season_detail/?choice=3 when what I what is something like /season_detail/?choice=1983
I assume I need to write that into views.py, but after reading through the Django docs and searching through the forum here and trying several approaches I'm more confused than ever.
It looks like you're mixing forms.Form and forms.ModelForm in class season_choice based on your use of forms.Form but also declaring a Meta class.
If you need a different form widget than the model default, you can over ride it in the Meta class if using a ModelForm. When using ModelForms it's best practice to explicitly list the fields to be displayed so that future fields (potentially sensitive ones) are not added by default.
class SeasonForm(forms.ModelForm):
class Meta:
model = Season
fields = ['year']
widgets = {
'year': forms.widgets.Select(),
}
Django models also have a Meta class that will allow you to provide a default ordering:
class Season(models.Model):
year = ...
class Meta:
ordering = ['-year']
If you don't want the entire Model class to have that ordering, you can either change this in your view or create a proxy model, then in your form use model = SeasonYearOrdering.
class SeasonYearOrdering(Season):
class Meta:
ordering = ['-year']
proxy = True
Another item of interest is the hard coded url in your template. You can give the urls in your urls.py names. Then in your template, you can reference these names so that if your urls.py path ever changes, your templates refer to the name and not the hard coded path.
So:
<form action="/season_detail/{{ choice.year }}" method="get">
Becomes (season_detail is the name from urls.py):
<form action="{% url "season_detail" choice.year %}" method="get">
You may change the value of option by adding to_field_name='year' to the choice ModelChoicefield in the form.
So you'll get
<option value="1981">1981</option>
<option value="1982">1982</option>
<option value="1983">1983</option>