I have this in my views.py:
def announcements(request):
return render_to_response('events.html', {
'posts1': Blog.objects.filter(category__title="Announcements")
}, context_instance=RequestContext(request)
)
And this in my base.html:
{{ posts1 }}
But nothing from the above request context gets rendered when I load the home page.
Edit 1:
It looks like I am on a wrong path here. My aim is to display the posts under "announcement" category throughout my website in a fixed sidebar. Whichever page is opened the sidebar in that page should contain only posts from "announcement" category. Any suggestion for how to achieve it?
Create an inclusion template tag and use it in templates where you want to display that sidebar.
Related
I'm creating a django-based website where page content is stored in a model textfield with a detail view of the model displaying it. How can I put {% url %} tags in the content to link to other pages without hard coding links?
Putting the tag into the textfield will just print the tag as plain text. (or if inside an href create a broken link)
Other options are
parsing the content manually inside the view and replacing the tags with the correct url
using some django supplied string parser to create the links before sending to the template
maybe there is a way to do it in the template with a filter or tag around the variable.
I could probably do the manual way but I am hoping there is a django way that I am missing.
class Page(models.Model):
content = models.TextField(blank=True)
class PageView(DetailView):
model=Page
context_object_name='page'
{% extends "base.html" %}
{% block content %}
{{ page.content|safe }}
{% endblock %}
Edit for clarity:
Content in admin
What it renders
What it should render
Edit 2:
I was able to find a solution to the second option thanks to this answer on another question. Using that template_from_string function I rendered the page content as a template then replaced the content in the context with the rendered result.
class PageView(DetailView):
model=Page
context_object_name='page'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
# Add to context here
context['page'].content = template_from_string(context['page'].content).render(context)
return context
your url's will have a name as shown below-
path('page//',PageView.as_view, name="page-detail")
and in your Page Detail
hope this is what your asking for
Let see if I understood you well, do you want django to show you a url as such and not as plain text?
If you want to avoid django to show you the data as plain text, you can use the escape filter as follows: {{string | escape}}
Check this page for more details about django filters and tags
The example setup from the 'effective django' tutorial works in the following manner:
On the contacts_list page, the user clicks 'delete'.
The DeleteView re-directs to the confirm delete page.
The user clicks the confirm (or cancel) button and is redirected back to contacts_list page.
What I would like to do instead is:
click 'delete' and pop up a bootstrap modal
confirm delete (or cancel) in the modal
then return to the contacts_list page.
Additionally I would like to do the same for edit and create. Delete just seemed like the simplest case.
Looking up similar topics, it appears modals don't really call a link(/view) and jquery/ajax should be able to solve the issue. I am still a little unclear on the concepts and best practices. Any insights appreciated.
url.py
url(r'^$', contacts.views.ContactListView.as_view(), name='contacts-list',),
url(r'^new$', cts.views.CreateContactView.as_view(), name='contacts-new',),
url(r'^edit/(?P<pk>\d+)$', contacts.views.UpdateContactView.as_view(), name='contacts-edit',),
url(r'^delete/(?P<pk>\d+)$', contacts.views.DeleteContactView.as_view(), name='contacts-delete',),
url(r'^detail/(?P<pk>\d+)$', contacts.views.ContactDetailView.as_view(), name='contacts-view',),
views.py
class ContactListView(ListView):
model = Contact
template_name = 'contact_list.html'
class DeleteContactView(DeleteView):
model = Contact
template_name = 'delete_contact.html'
def get_success_url(self):
return reverse('contacts-list')
contact_list.html
{% for contact in object_list %}
<li><h3>{{ contact.first_name }} </h3>
edit
delete
</li>
{% endfor %}
You need to omit the validation step provided by django's DeleteView.
Do not bother sending ajax calls.
First, figure out how to display the modal form.
Then you just have to declare the form method as POST (GET would give you the confirmation template) and leave the action as it is.
Im trying to insert the registration-form template from django-registration in another html document.
The original Registration template it's working perfectly fine and users are saved in the DB:
This is what happend when i try to insert the registration form in any other html document using {% extend registration/myRegistrationFormTemplate.html %}. Fields are not showed and the submit button don't work.
Also, this is what happend when i try to load myRegistrationFormTemplate.html using the Jquery method .load. Fields are showed but the submit button don't work.
The question is: Why this is happening? and what's the usual procedure to do this?
You might need to use include which allows you to render the included page with the current context. However, this totally depends how you design your templates structure and how they extends other templates. This answer might explain the difference: https://stackoverflow.com/a/2863753/2074398
Thanks FallenAngel you were right, i was missing the view info. And thanks for telling me about "include" almalki, now all it's working right. In my project im using 2 forms in this view and a jquery modal window. To simplify my solution i'll only use one form. I hope this will be useful for someone.
SOLUTION:
View of the template you'll include the form
def patrimonio_view(request,
template_name='home/patrimonio.html'):
#OTHER DB QUERYS
pat = patrimonio.objects.all()
ciu = ciudad.objects.all()
if request.method == 'POST':
if "Registrar_usuario" in request.POST:
#USER REGISTRATION FORM RELATIVE
return register_usuario()
if "Registrar_comerciante" in request.POST:
#MERCHANT REGISTRATION FORM RELATIVE
return register_comerciante()
#RENDER
return render_to_response(template_name,{
'patrimonio':pat,
'ciudad':ciu,
}, context_instance=RequestContext(request))
urls.py
url(r'^patrimonio/$','patrimonio_view',
{'backend_registro_usuario': 'Hesperides.apps.accounts.regbackend_usuario.DefaultBackend','form_class_usuario':RegistrationForm_usuario}, name='vista_patrimonio'),
in the template you will include the form:
{% include "registration/registration_form_usuario.html" %}
Can a non-form web page be included in a django SessionWizardView?
For example, I want the user to FillOut Form1, Form2, Then View a web page (in same session) (click next), and then Form3? All this while maintaining the same session.
If so, how is this best accomplished? Any examples or snippets?
There's a fairly easy hack for this. Create a plain old form that has one field that is hidden from the user, has no content, and isn't required.
I do this:
class BlankForm(forms.Form):
nothing = forms.CharField(required=False, widget=HiddenInput)
Include it in your SessionWizardView call just like the other pages:
SessionWizardView.as_view([Form1, Form2, BlankForm, Form3])
In the template page you can use some logic like this to display info:
{% if wizard.steps.current == '2' %}
Whatever you want to show on the BlankForm
{% endif %}
For one of my models, I want to show extra content in the change_form. Basically, my model looks like this:
class News(models.Model):
...
class NewsFromSource(models.Model):
news = models.ForeignKey(News)
...
I want to add a 'search' button that, when clicked, triggers a web service request to an external news source, pulls down the available content, and lists all the news pieces contained. The user can then select one of the pieces to "attach" to the News currently edited in the admin interface (i.e. create a new NewsFromSource based on the content downloaded through the web service).
I am done with the web service. What is the best approach to implementing the search-button, list display for the results (I have a view and template that work, need to get those into the form somehow) and the saving part?
What I ended up doing is the following:
1)
I created a view for fetching search results, which boils down to this:
#/myproject/admin/views.py
#never_cache
def news_search(request):
#...query web service
if 'q' in request.POST:
search_term = request.POST['q']
else:
search_term = ''
news = NewsSearch()
news.search(search_term)
return render_to_response( 'news_search_results.html',
{ 'q': search_term,
'news': news.result_list,
'page': page,
'page_left': news.page_left,
'page_right': news.page_right}
)
2) I mapped the view:
#/myapp/urls.py
...
url(r'^myapp/news/search/$', views.news_search),
3) I extended change_form.html for the news model with the following code:
#/myproject/templates/admin/myapp/news/change_form.html
{% extends "admin/change_form.html" %}
{% block after_field_sets %}
...
{% csrf_token %}
<input type="text" name="q" id="news-search-term">
<div id="news-search-results"></div>
...
function submitSearchForm() {
$.post("/myapp/news/search/",
{ 'q': $('#news-search-term').val(),
'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val() },
function(data){
$('#news-search-results').html(data);
}
);
}
{{ block.super }}
{% endblock %}
4) I created an html template for displaying the results (news_search_results.html, see 1)
So basically I am sending an AJAX request from the admin page to a custom view to retrieve results from the webservice which then are displayed in a div.
Each element in the results list has a button that sends another request that stores the element with the news id as a ForeignKey.
I have no idea whether this is particularly against Django principles. But it seems to work alright.
Suggestions on doing this in a more "Djangonian" way are welcome.
We'll assume you have a related News model. Add that field to raw_id_fields of the modeladmin we're going to hack, then:
Overload the change_form template for this model, extend admin/change_form.html in admin/yourapp/yourmodel/change_form.html
Add javascript in that template to:
Hide the input and magnifier icon from the news raw id field form raw, you can do that in css too
Add something like a span with a button style in that form row that will open a popup when it is clicked
The popup it should open should be your working view/template with a form to select the news
When the user selects a news, the popup should do an ajax post request to get the news id, and close itself
the value is set to the raw id field input that is hidden, this is pretty tough but fear not someone (disclamer: I) published an article with the whole technical details, also found another one but I didn't test it
It's going to be quite some work. Patience and perseverance will be your best qualities for this mission B)