Django: rendering more than one view in a template - django

I am newbie in Django and didn't know how to render more than one view in a template. This is my case, I have a template (main.html) and I have 2 sections: a home page and one at the top where the user data (messages, log off, etc ...) will be displayed.
My question is this, can I make 2 partial views (_index.html and _userdata.html) and render them separately and display them in the template. In the same way that the "include" php or ASP.NET MVC partial views. Or spend the model or models to the template with all the information.
As I haven't explained well, an example of real life would be, Amazon or any online book store. Where you can see the books or products on the right side and have your shopping cart with your products shown. How would that Django? Have an HTML template and view the 2 models you send or you can do 2 separate views and are rendered in the same HTML template?

Those things are bound to the user, so you could get them in your parent templates.
Example:
parent.html
{{ request.user.get_something }}
define get_something(self) in the user model (your items in the cart, etc).
You can also do something like:
{% include 'elements/my_something.html' %}

Related

create new parent model in CreateView in django

i am new to django and to this site, so apologies if this has been solved before but i haven't found it
So i have 2 django models
ModelA(Model):
ModelB(Model):
modelA = ForeignKey(ModelA, on_delete=models.CASCADE)
A form for the ModelB
ModelBForm(ModelForm):
class Meta:
model=ModelB
exclude=()
and a view
createModelBView(CreateView):
model = ModelB
form_class = ModelBForm
the template only does
{{form}}
When rendered, there is a dropdown list for the ModelA field so I can choose from existing instances of the ModelA, but what if a new one needs to be created? In the admin there is an option next to edit or create a new ModelA in a popup. Is there an option to do this with CreateView?
Thanks
There is no built-in functionality like that.
However you can build it easily yourself.
You will have to add a link (or a HTML form) in your template which points to the URL corresponding to the view you implemented to create the given model.
Following is a very abstract example.
In your template:
<form>
{{csrf_token}}
{{ form }}
Create model A if you want
<input type="submit" value="Submit">
<\form>
In your urls.py
url(r'^models/createA/$', views.CreateModelAView.as_view(), name="optional")
In your views.py
createModelAView(CreateView):
model = ModelA
form_class = ModelAForm
Then you'll need to create a form called ModelAForm.
On a different note, I'd suggest to start off with functional views if you're new to Django. It is more coding but you get a better feel of what's going on
In the admin there is an option next to edit or create a new ModelA in a popup. Is there an option to do this with CreateView?
No, not built in. That functionality in the admin involves a lot of front-end work involving templates and routing that would have to come from somewhere; since a Form/ModelForm instance can't assume it has access to the admin (which is a contrib module, may not be enabled, and is permission-sensitive), the infrastructure required for that can't be assumed to be available in the general case.
Keep in mind that {{ form }} doesn't even render <form> tags or any kind of submit element. It's intended to be a very, very basic way to render a very, very basic set of fields, while the admin is built specifically to be a (reasonably) powerful, flexible way to put a UI in front of your models.
You could certainly build that functionality yourself, or find a reusable app that does the same thing, but there is no facility distributed with Django to generate it automatically.

submit multiple forms in a single django template

I have a django project with a single html template. i am want to know if it is possible to pass multiple forms into a single template. I want to process the form differently for each of the forms that are passed. Is that possible to do and how can I differentiate the different forms for processing... if anyone can help, I would much appreciate it.
You can. all the forms can be rendered inside single . If you want to submit them in different events, you can add multiple submit buttons and give name attribute for each of them. An in your view you can check:
if 'submit_button_name' in request.POST:
If you just want to submit them altogether, use just one submit button.
To render mulitple model forms in same template you can do like this:
<form>{{ form1.as_p }} {{ form2.as_p }}</form>

Can I limit the visible Collections in the Wagtail Admin Image Chooser?

I have a few Groups and Collections setup to take advantage of the Collections feature in wagtail.
I have limited collection A to Administrators only.
After logging in as a non-Administrator and clicking on the 'CHOOSE AN IMAGE' button to bring up the image chooser, there's a drop down for 'Collection' and it includes all of my collections, including the restricted collection A.
Is it possible to only show collections and images that the user owns similar to how the 'Images' menu item works?
Wagtail: 1.12.2
Django: 1.8.18
I know it has been a while since this question was asked but hopefully this answer helps some people.
Solution Overview
Wagtail 1.10 (as at this post, 2.10 is in development) introduced a helpful hook called construct_image_chooser_queryset. This hook will intercept the images before being returned to the image chooser modal (used across all of Wagtail admin) and lets a developer customise what images are returned.
The hook also has access to the request, from there you can work out the user and build up your image query accordingly.
The other part of your question involved the collections drop-down field, this requires a bit of Django template work but is doable without too much extra complexity. Any Wagtail admin template can be overridden with a custom template, simply name it using the existing template path.
The Django shared template (include) that is used to render the collection dropdown, as at posting is wagtail/admin/templates/wagtailadmin/shared/collection_chooser.html
Example Code
Note: the code is not a full solution as the question did not have the collection model changes but will be a good start hopefully.
1. Wagtail image chooser queryset hook
Based on the example in the hooks documentation
file: wagtail_hooks.py
from wagtail.core import hooks
#hooks.register('construct_image_chooser_queryset')
def show_my_uploaded_images_only(images, request):
# Example: Only show uploaded images based on current user
# actual filtering will need to be based on the collection's linked user group
images = images.filter(uploaded_by_user=request.user)
return images
2. collection chooser template override
2a file: ../templates/wagtailadmin/shared/collection_chooser.html
We want to override the template and redirect it to a custom one ONLY IF images are present in the template's context
{% extends images|yesno:"base/include/images_collection_chooser.html,wagtailadmin/shared/collection_chooser.html" %}
2b file: ../templates/base/include/images_collection_chooser.html
This template will only be used if there are images in the context
Here we revise the context to remove images and filter collections then render the original Wagtail admin template
{% load filter_with_permissions %}
{% with images=None %}
{% with collections=collections|filter_with_permissions:user %}
Images Only Collection Template:
{% include "wagtailadmin/shared/collection_chooser.html" %}
{% endwith %}
{% endwith %}
2c file: bakerydemo/base/templatetags/filter_with_permissions.py
Here we make the Django template tag that does the collection filtering
from django import template
register = template.Library()
#register.filter(name='filter_with_permissions')
def filter_with_permissions(collections, user):
""" filter the collections based on current user """
return collections.filter(name__startswith='B') # actual filter to be done

Django Loading data independantly in a partial

I have some partial templates which I load in on various pages and sometimes the inclusion of these partials is dynamic, these have their own related models.
At present I am passing models via views to the main page, but is there not a way to load data for these partials independant of the parent page and view?
Just seems like I am duplicating code in the views which cant be right!
Can I not create a custom tag or something which would allow me to load data into the partial irrespective of the data passed in the parent page and its view?
A good example of this is a partial for "latest posts" which exists in a sidebar partial and loads on many different parent templates
Cheers
Kevin
A custom template tag can do this for you. You could write an inclusion tag, which will output the rendered template directly:
# yourapp/templatetags/appname_tags.py
def latest_posts(num_posts):
posts = Post.objects.all()[:num_posts]
return {'posts': posts}
register.inclusion_tag('yourapp/partials/latest_posts.html')(latest_posts)

Django: where can I find the template that renders the fields of the admin page?

I want to change the shape of some fields showed in the admin site.
I found that the template that manage everything is change_form.html with fieldset.html but I cannot find where the fields are actually transformed in html.
Basically I want to change the field of the foreign key adding a link to another page.
Do you have any idea?
Thanks,
Giovanni
The HTML for a given field is handled by its widget in the render function. If you want to customize the look of a field you could create a custom widget which has the additional HTML you need in the render.
You can check out the render some of the built in widgets in django/forms/widgets.py (links to the Django trunk).
In fieldset.html, the code {{ field.field }} renders the field's HTML representation. to achieve what you want, you'll probably need to define your own widget. you can take a look at admin's widgets.py