I written a small comments app.
Part of forms.py:
class TinyCommentForm(CommentSecurityForm):
comment = forms.CharField(widget=TinyMCE(attrs={'cols': 80, 'rows': 30}))
Part of models.py:
class TinyComment(BaseCommentAbstractModel):
comment = tinymce_models.HTMLField()
Part of template which using TinyCommentForm:
{% if user.is_authenticated %}
{% get_comment_form for object as form %}
<form action="{% comment_form_target %}" method="POST">
{{ form.comment }}
{{ form.content_type }}
{{ form.object_pk }}
{{ form.timestamp }}
{{ form.security_hash }}
<input type="submit" name="post" class="submit-post" value="Add" />
</form>
{%endif%}
Here I can adding and saving comments, but only without tinymce editor and that is working fine.
If I add to my comment form in template field: {{form.media}} tinymce editor show up, but if I write something there, my POST form seems to be without content, saying that I need to write something to it.
Giving {{form.media}} to <HEAD> sector does not working even if I render through my view the TinyCommentForm as 'form' to this template.
So i tried to import JS more manually and I add to <HEAD> section(using Django 1.3):
<script type="text/javascript" src="{{STATIC_URL}}js/tiny_mce/tiny_mce.js"></script>
Then I check that the src link and it is correct.
So next I add second line there:
<script type="text/javascript" src="{% url tinymce-js "NAME" %}"></script>
Then I create NAME/tinymce_textareas.js with JS code and add containing this folder to TEMPLATE_DIRS. MY urls including tiny_mce urls. But still without results.
Does somebody could illumine me a little?
Got it working good. Answer:
{% if user.is_authenticated %}
{% get_comment_form for object as form %}
<form action="{% comment_form_target %}" method="POST">
{{ form.media }} <!-- This is needed -->
{{ form.comment }}
{{ form.content_type }}
{{ form.object_pk }}
{{ form.timestamp }}
{{ form.security_hash }}
<input type="submit" name="post" class="submit-post" value="Add" />
</form>
{%endif%}
And any JS in section was needless.
But the devil lives in my forms.py which should looks like this:
class TinyCommentForm(CommentSecurityForm):
comment = forms.CharField(widget=forms.Texarea)
And now everythigng works properly.
Edit: The reason of why my comment form need to using widget=forms.Texarea is, i think, that my texareas.js has mode : "textareas". If I am wrong please correct me.
Related
I have the following component in a django template
<div class="trow" v-for="(item, idx) in data">
</div>
Now if I try to write the following inside the div
{{ item.co.name }}
I won't get the value, I will have to write the following to get the value
{% verbatim %} {{ item.co.name }} {% endverbatim %}
Now my problem is that I have to do something with this value so I wrote a simple filter like this
from django import template
from django.templatetags.static import static
register = template.Library()
#register.filter
def define(val=None):
return static(f"images/{val.lower()}.svg")
but I can't do the following
<div class="trow" v-for="(item, idx) in data">
{% verbatim %} {{ item.co.name | define }} {% endverbatim %}
</div>
I've also tried a lot of combinations with no luck, how can I solve this?
Edit: I changed the data and added the path I want inside it, now I want to use this value inside an img tag like this
<img src="{{ item.icon_path }}">
but this again won't give me the value because it needs a verbatim tag, and doing it like this
<img src="{% verbatim %}{{ item.icon_path }} {% endverbatim %} ">
I am working with forms sets, I was wondering how one could use
<input type='hidden'
inside a form set. (Django formsets allow us to use multiple forms instances of a single form)
Its easy to do in normal single form where you just put the field with the type='hidden' and name='fieldname' e.g.
<input type='hidden' name='user' value='{{request.user.id}}'>
Dealing with formsets is a bit catchy, how to achieve the same behavior with the forms sets?
Views.py
PictureFormSet = modelformset_factory(Picture, form=UpdatePictureForm, extra=0)
formset_qset = Picture.objects.filter(id__in=[15, 16, 17, 18, 19, 20])
if request.method == POST:
ctx['form_set'] = PictureFormSet(request.POST, queryset=formset_qset)
ctx['form_set'].save()
ctx['form_set'] = PictureFormSet(queryset=formset_qset)
return render_to_response('temp tabs.html', context_instance=RequestContext(request, ctx))
Template
<form method="POST" action="" class="form-horizontal">
{% for form in form_set %}
{{form.id}}
<div class="form-group">
<label class="col-lg-2 control-label">
{% with form.meta_data.value|load_meta_data as meta %}
<div class="portfolio-item video-container">
<a class="" href="{% url 'view_image' form.id.value %}?in=pro">
<i style="background-image: url({{ meta.image_size.thumbnail_small }});"
class="ds-thumbnail-container"></i>
</a>
</div>
{% endwith %}
</label>
<div class="col-lg-8 ">
{{ form.name }}
</div>
</div>
{% endfor %}
{{ form_set.management_form }}
{% csrf_token %}
<input type="submit" value="Submit">
</form>
Explanation
Here in this code, We are rendering images from the database for editing there names. we have url information inside the meta_data, so we have selected
fields=['id', 'meta_data', 'name']
We want to change/Update the name, but not the meta_data
This code works fine for the most part, but how i want to keep one field unchanged for the modal?
I have meta_data field that I am using in the template, but i do not want that field to be modified, that value should be in the form like this
{{form.meta_data}}
This turns it into text area, with different name and id. and it expects it be changing. but i want to declare a hidden field and sets its value to the form.meta_data.value
If you have any questions regarding this please do not hesitate to ask.
Thanks.
I'm very new to Django and not super familiar with web programming in general, so it's very likely that there is an easy fix to my problem that I'm just unaware of.
My web app is a photo gallery. People can click on a photo to see an enlarged version with buttons on either side for older or newer pictures. In addition, the photos in the gallery can be sorted by tags, which are passed along as URL parameters.
My problem is that when I click on one of the submit buttons, Django replaces the parameters in my URL with the name of the button, thus destroying my reference to what tag I was using. For example, "127.0.0.1:8000/gallery/view/6/?tag=people" upon clicking next, gets converted to "127.0.0.1:8000/gallery/view/6/?older=Older" when it's trying to process the URL.
Code from my HTML:
<form action="/gallery/view/{{ photo.id }}/?tag={{ tag }}" method="get">
{% if has_newer %}
<input type="submit" name="newer" value="Newer">
{% endif %}
<img src="{{ photo.photofile.url }}">
{% if has_older %}
<input type="submit" name="older" value="Older">
{% endif %}
</form>
In my view.py I pass in the tag plus other information in a render_to_response, but I'm not sure how to/if I can reclaim it while handling the buttons.
render_to_response('item/view.html', {'photo':photo, 'tag':tag, 'related_tags': related_tags, 'related_photos': related_photos, 'has_newer': has_newer, 'has_older': has_older}, context_instance=RequestContext(request))
Here's the view.py code for processing the buttons:
if 'newer' in request.GET:
if has_newer:
return HttpResponseRedirect('/gallery/view/%s/?tag=%s'%(newer[1].id, tag))
else:
return HttpResponseRedirect('/gallery/')
if 'older' in request.GET:
if has_older:
return HttpResponseRedirect('/gallery/view/%s/?tag=%s'%(older[1].id, tag))
else:
return HttpResponseRedirect('/gallery/')
<form action="/gallery/view/{{ photo.id }}/" method="get">
{% if has_newer %}
<input type="submit" name="newer" value="Newer">
{% endif %}
<!--This will append a tag parameter with given value to the querystring -->
<input type="hidden" name="tag" value="{{ tag }}">
<img src="{{ photo.photofile.url }}">
{% if has_older %}
<input type="submit" name="older" value="Older">
{% endif %}
</form>
Note that the query string is removed from action (as it won't be used) and the older and newer parameters will still be sent along.
I am new to django .
I am facing a small problem but unable to solve it.
In my template when I try to access any variable using {{ }} but it returns blank while displaying something as detailview.whereas it works fine in listview.
CODE:urls.py
urlpatterns = patterns('',
url(r'^$', ListView.as_view(
queryset=Profile.objects.all().order_by("First_Name"),
template_name="STUDENT_REGISTRATION.html")),
url(r'^(?P<pk>\d+)/$',DetailView.as_view(
model=Profile,
template_name="Profile.html")),
TEMPLATE:
{%extends "base.html" %}
{% block content %}
<h2>Registration No. :- {{ Profile.Registration_No }} <br>
Full Name : {{ Profile.First_Name }} {{ Profile.Last_Name }} </h2>
<div class="Profile_meta">
{{ Profile.Date_of_Birth}}
</div>
<div class="Profile_body">
{{ Profile.Permanent_Address|safe|linebreaks }}
</div>
{%endblock%}
Plz help..
You should refer to your Profile instance as:
{{ object.First_Name }} {{ object.Last_Name }}
By the way, take a look at PEP8, try to keep CamelCaseNames for class names and underscores_names for instances. It will make your code easier to read.
In Django template I used:
<form action="/user" method="post">{% csrf_token %}
{{ form.as_p|safe }}
<input type="submit" value="Submit" />
</form>
But error when I change to jinja2 template engine:
Encountered unknown tag 'csrf_token'
My question: csrf_token protection in jinja2 is required?
If required, how to do this?
Thanks in advance!
It seems Jinja2 works differently:
Use <input type="hidden" name="csrfmiddlewaretoken" value="{{ csrf_token }}">
where in Django templates you use {% csrf_token %}
source : http://exyr.org/2010/Jinja-in-Django/
I know this is an old question, but I wanted to update it with the proper way to support the csrf_token when using the new django.template.backends.jinja2.Jinja2 available in Django 1.8+. Using the django template backend you would have called {% csrf_token %}, but using the Jinja2 backend you will call it using {{ csrf_input }} (you can get just the token value instead of the token input using {{ csrf_token }}).
You can see the details in the django.template.backends.jinja2.Jinja2 source
in django 2.x with jinja2 templates engine you get the value of the token with {{ csrf_token }} and the complete hidden input tag with {{ csrf_input }}
source: https://django.readthedocs.io/en/2.1.x/ref/csrf.html
example:
<form action="..." method="post">
{{ csrf_input }}
...
</form>
I use Coffin.
And have same problem when use:
from coffin.shortcuts import render_to_response
return render_to_response('template_name_here.html', context)
try to use instead:
from coffin.shortcuts import render
return render(request, 'template_name_here.html', context)
You don't need to do anything special anymore. csrf_token is supported in django-jinja and works out of the box.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>test</title>
</head>
<body>
<p>This should add a hidden input tag with the token. use it in your forms</p>
{% csrf_token %}
</body>
</html>
I had the same problem, and what I noticed is that the CSRF context processor isn't in the list of the default loaded processors. After adding 'django.core.context_processors.csrf' to the TEMPLATE_CONTEXT_PROCESSORS in setting.py I could use the {% csrf_token %} template tag normally.