Django Generic Createview : Add another object to template - django

I'm trying to add additional data to my template named "equipment_form" linked with my view CreateEquipment (CreateView generic django)
So, my model Equipment possess a subcategory. And my model subcategory possess a category.
For UX reasons, I want my user to chose the category of the equipment first, then the subcategory. In order to do this, I need to get in the view the whole content of the
category table and give it to the template. And I have some trouble to figure out how I can do it.
I will really appreciate the help of the community! Thank you.
So atm my view look like this :
class EquipmentCreate(CreateView):
#category list not passed to the template
category_list = Category.objects.all()
model = Equipment
success_url = reverse_lazy('stock:equipment-list')
EDIT : I found the answer here :
Django - CreateView - How to declare variable and use it in templates
Thank you anyway :)

Found* the answer here:
Override get_context_data and set context_data['place_slug'] = your_slug
Something like this:
def get_context_data(self, **kwargs):
context = super(PictureCreateView, self).get_context_data(**kwargs)
context['place_slug'] = self.place.slug
return context
Some more info on this in the Django docs.
*Posting OP's comment and edit as answer

Related

How to get related objects from one to many relationship for display in ListView and be able to filter?

I'm looking at this tutorial from the Mozilla library. I want to create a list view in admin based on a database relationship. For example I have a Vehicle model and a statusUpdate model. Vehicle is a single instance with many statusUpdates. What I want to do is select the most recent statusUpdate (based on the dateTime field I have created) and have that data available to me in the list view.
The tutorial mentions:
class Vehicle(models.Model):
class statusUpdate(models.Model):
vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE)
Question: How could I do a list view with model relationships and be able to filter by fields on the child relationship and pass to the view?
Here's what I wanted in a Class Based View (CBV), my explanation of my issue was not very clear.
def get_context_data(self, **kwargs):
get_context_data is a way to get data that is not normally apart of a generic view. Vehicle is already provided to the View because its the model defined for it, if you wanted to pass objects from a different model you would need to provide a new context, get_context_data is the way to do this. statusUpdate is a model with a foreign key to Vehicle. Full example below.
class VehicleDetail(generic.DetailView):
model = Vehicle
template_name = 'fleetdb/detail.html'
def get_context_data(self, **kwargs):
# Call the base implementation first to get a context
context = super(VehicleDetail, self).get_context_data(**kwargs)
context['updates'] = statusUpdate.objects.filter(vehicle_id=1).order_by('-dateTime')[:5]
return context
I don't think that solves your problem entirely. You used this:
context['updates'] = statusUpdate.objects.filter(vehicle_id=1).order_by('-dateTime')[:5]
This will only result in a list of statusUpdates where vehicle_id is set to 1. The part I was struggling with is how to get the primary key (in your case the actual vehicle_id). I found this solution:
vehicle_id = context['vehicle'].pk # <- this is the important part
context['updates'] = statusUpdate.objects.filter(vehicle_id=vehicle_id).order_by('-dateTime')[:5]
I discovered the context object and it contains the data which has already been added (thus you need to call super before using it). Now that I write it down it seems so obvious, but it took me hours to realize.
Btw. I am pretty new to Django and Python, so this might be obvious to others but it wasn't to me.

Passing URL variables to a class based view

I have just started messing with class based views and I would like to be able to access variables from the URL inside my class. But I am having difficulties getting this to work. I saw some answers but they were all so short I found them to be of no help.
Basically I have a url
url(r'^(?P<journal_id>[0-9]+)/$',
views.Journal_Article_List.as_view(),
name='Journal_Page'),
Then I would like to use ListView to display all articles in the particular journal. My article table however is linked to the journal table via a journal_id. So I end up doing the following
class Journal_Article_List(ListView):
template_name = "journal_article_list.html"
model = Articles
queryset = Articles.objects.filter(JOURNAL_ID = journal_id)
paginate_by = 12
def get_context_data(self, **kwargs):
context = super(Journal_Article_List, self).get_context_data(**kwargs)
context['range'] = range(context["paginator"].num_pages)
return context
The journal_id however is not passed on like it is in functional views. From what I could find on the topic I read I can access the variable using
self.kwargs['journal_id']
But I’m kind of lost on how I am supposed to do that. I have tried it directly within the class which lets me know that self does not exist or by overwriting get_queryset, in which case it tells me as_view() only accepts arguments that are already attributes of the class.
If you override get_queryset, you can access journal_id from the URL in self.kwargs:
def get_queryset(self):
return Articles.objects.filter(JOURNAL_ID=self.kwargs['journal_id'])
You can read more about django’s dynamic filtering in the docs.

What is the difference between using TemplateView and ListView in Django?

In the database, I have a set of questions. I want to display every question in a collapsible item as a list. Previously I used TemplateView:
class questionmanager(TemplateView):
template_name = 'questionmanager.html'
questions = Question.objects.all()
def get_context_data(self, **kwargs):
context = ({
'questions': self.questions,
})
return context
Then, I read that using ListView is better practice to represent a list of objects. Then I changed my class to this:
class QuestionListView(ListView):
model = Question
def get_context_data(self, **kwargs):
context = super(QuestionListView, self).get_context_data(**kwargs)
return context
In the old template I used this for loop:
{% for question in questions %}
I thought I wouldn't need to use a for loop when I use ListView instead of TemplateView; but I couldn't list the items without a for loop. I found an example here, and it seems to me, the only difference is that in the for loop we use object_list ( {% for question in **object_list** %}) instead of using argument that we pass in the context.
I really don't see so much difference between using TemplateView and ListView - after spending an hour on this. I'd appreciate if someone explains why using ListView instead of TemplateView is a better practice (in this case).
Thanks in advance.
For simple use cases such as this, there isn't much difference. However, the ListView in this example is much cleaner as it can be reduced to:
class QuestionListView(ListView):
model = Question
considering you aren't putting anything in the context. TemplateView's as a base view are rather rudimentary, and provide a much smaller set of methods and attributes to work with for the more complex use cases, meaning you have to write more code in such instances. If you take a look and compare both views TemplateView and ListView here, you can see the difference more clearly. Pagination is a good example, to paginate a ListView you simply set the paginate_by attribute and modify your template accordingly.
Also note, you can change the default name object_list by setting context_object_name in the 'ListView'
The major difference is that ListView is best to list items from a database called model, while TemplateView is best to render a template with no model. Both views can be very concise with different meaning.
Below is sample of a list view in it simplest form
Class SampleListView(ListView):
model = ModelName
This will give you a context variable object_list and a template name in the form ("app_name/model_name_list.html") automatically that can be used to list all records in the database.
However, the TemplateView in its simplest form is
class SampleTemplateView(TemplateView):
template_name = 'app_name/filename.html'

Pre-selecting multiple checkboxes in Django forms

Very similar to this question, but I tried the accepted answer and it did not work. Here's what's going on.
I have a form for tagging people in photos that looks like this:
forms.py
class TaggingForm(forms.Form):
def __init__(self, *args, **kwargs):
queryset = kwargs.pop('queryset')
super(TaggingForm, self).__init__(*args, **kwargs)
self.fields['people'] = forms.ModelMultipleChoiceField(required=False, queryset=queryset, widget=forms.CheckboxSelectMultiple)
...
models.py
class Photo(models.Model):
user = models.ForeignKey(User)
...
class Person(models.Model):
user = models.ForeignKey(User)
photos = models.ManyToManyField(Photo)
...
I want users to be able to edit the tags on their photos after they initially tag them, so I have a page where they can go to view a single photo and edit its tags. For obvious reasons I want to have the already-tagged individuals' checkboxes pre-selected. I tried to do this by giving the form's initial dictionary a list of people I wanted selected, as in the answer to the question I linked above.
views.py
def photo_detail(request,photo_id):
photo = Photo.objects.get(id=photo_id)
initial = {'photo_id':photo.id, 'people':[p for p in photo.person_set.all()]}
form_queryset = Person.objects.filter(user=request.user)
if request.method == "POST":
form = TaggingForm(request.POST, queryset=form_queryset)
# do stuff
else:
form = TaggingForm(initial=initial, queryset=form_queryset)
...
When I try to initialize people as in the above code, the form doesn't show up, but no errors are thrown either. If I take the 'people' key/value pair out of the initial dictionary the form shows up fine, but without any people checked.
Also I'm using Django 1.5 if that matters. Thanks in advance.
What you could do is simply use django forms to handle all of this for you. Please refer to this question. Ideally it boils down to lettings djnago handle your forms and its validation and initial values.
Now this is actually a really good practice to get used to since, you're dissecting all your logic and your presentation. Its a great DRY principle.

How to pass in a parameter to the form within the formset?

I would like to create a formset, where each form has a dropdown pointing to a set of sales items.
Model:
class SalesItem(models.Model):
item_description = models.CharField(max_length=40)
company = models.ForeignKey(Company)
Here I create a form with a dropdown, hoping to pass in the company as a source for the dropdown. Hold on to this thought, as I think that is not possible in my scenario.
Form:
class SalesItemFSForm(Form):
sales_item = forms.ModelChoiceField(required=False, queryset = '')
def __init__(self, company, *args, **kwargs):
super(SalesItemFSForm, self).__init__(*args, **kwargs)
self.fields.sales_item.queryset = company.salesitem_set.all()
Now within my view I would like to create a formset with this form:
formset_type = formset_factory(SalesItemFSForm, extra=0)
The problem becomes right away clear, as there seem to be no way that I could pass in the company to determine the source for the dropdown.
How am I supposed to do this?
Many Thanks,
Update:
it seems Jingo cracked it. :)
A ModelForm works better than a Form. On top of it I had to add fields = {} to SalesItemFSForm, to make sure that the SalesItem's fields are not showing up in the template. Because all we are interested in is our dropdown (SalesItem).
So far so good. But now I see as many dropdowns shown as I have Salesitems. It shouldn;t show any unless the user presses a jquery button.
And I think this is the problem, we should NOT pass in
formset_type = modelformset_factory(SalesItem, form=SalesItemFSForm, extra=0)
Because our form doesn't need any instance of the SalesItem. We need a dummy Model.
That was the reason I tried to solve it initially with classic Formset instead of ModelFormset. So its kind of half way there. :)
Update 2:
Jingo, good point. Effectively I was thinking of a custom save, where I just see how many formsets are added by the user via jQuery and save it myself within the view. Literally SalesItem is a ManyToMany field. But the standard M2m widget is horrible. Hence I wanted to replace it with formsets, where each salesItem is a dropdown. The user can then add as many dropdowns (forms in formset) to the page and submit them. Then I would add the relationship in the view.
class DealType(models.Model):
deal_name = models.CharField(_(u"Deal Name"), max_length=40)
sales_item = models.ManyToManyField(SalesItem)
price = models.DecimalField(decimal_places=2, max_digits=12)
Hope this makes it clear. Maybe there is an easier way to do this. :)
Btw I also found this excellent jquery snippet code how to add/remove forms to/from a formset.
Update 3:
Indeed when instantiating the object like this, we would only get one form in the formset and can add more via jquery. Perfect!! Unless there is an easier way to achieve this. :)
salesitem_formsets = formset_type(queryset=SalesItem.objects.filter(pk=1))
However this comes back hunting you in the request.POST, since you can't just do:
salesitem_formsets = formset_type(request.POST)
It still requires the queryset to be set. Tricky situation...
I hope I understood the goal you want to achieve right. Then maybe you could use ModelForm and its available instance like this:
class SalesItemFSForm(forms.ModelForm):
class Meta:
model = SalesItem
def __init__(self, *args, **kwargs):
super(SalesItemFSForm, self).__init__(*args, **kwargs)
self.sale_items = self.instance.company.salesitem_set.all()
self.fields['sales_item'] = forms.ModelChoiceField(queryset=self.sale_items)
This is untested though and just a thought. I hope this leads into the right direction, but if its totally wrong, let me know and i will remove my answer, so that others wont be confused :).