Please, I would like to render a varible in django template, kind of {{ user.name }} inside of a textfield from database, that I filled up on the django admin. like this
how can I manage to achieve it please, thank you all, have a good day.
If you are using custom form then try using
value={{ user.name }}
and if you are letting Django render the form for you as like "form.as_p" then you can try
form_instance = Form(request.POST)
and send the form instance to the template
After a while of looking, I found out that the right solution of accomplishing such a thing is by creating a filter or tag and affecting it to the content rendered from the database based on the Django documentation link to create custom filters and tags, I created a filter that takes the content as a variable and scanned whenever I find the variable I replace it with the content from the database
# This code goes in the filter logic
values = model.objects.all()
content.replace('{{ user.name }}',values.name)
# This is how the content is rendered on the template
{{content | filter_name}}
Related
I have a Django template that renders a table comprising Django formsets.
Template (simplified)
<table id = 'my_table'>
{% for form in my_formset %}
<tr><td>{{form.my_field}}</td></tr>
{% endfor %}
</table>
Now, I have a Jquery code which looks something like this:
$(document).on('change', '#my_table tr input[type = text], input[type = number]', function(){
// currently the following code handles save event
// $.post ('/save_my_form/', $form.serialize())
});
And the corresponding Django view
def save_my_form(request):
# .......
for form in order_draft_formset:
if form.is_valid():
form.save()
# .......
The problem with this approach is that I modify only one single input element in one single form, whereas the Django view loops through entire formset. The question is, is there any built-in Django way to fetch the form within which the modified input is localized, so that I save only this exact form in my view without going through the entire formset. I feel that Jquery must somehow submit some info via post-request parameters that would help Django do that. As for now, I am thinking of parsing the automatically Django-generated id, f.e, id_form-5-my_field, and getting "5" out of it in Jquery and passing this "5" to Django. But I have a terrible feeling that this is a "dirty" method, and there must be a cleaner way to do that. Any ideas on this ?
if form.has_changed():
if form.is_valid():
form.save()
Duplicate question to Django-Taggit in Edit Form. However, the answer doesn't work for me.
I'm using Django Taggit in a form. The form is populated by an instance of an object that has Django Taggit enabled.
In my template, the forms tag input field value is set like so:
value="{{ form.tags.value|default_if_none:"" }}"
This results in a string value in the rough format of:
value="[<TaggedItem: foo tagged with bar>]"
If I render the form using basic Django form rendering ( i.e. {{form}} ), the tag field value is rendered correctly ( i.e. "tag1, tag2" ). Strangely, this is the opposite to what the poster of Django-Taggit in Edit Form was experiencing. For them, {{ form }} wasn't rendering the value correctly, but for me, it is.
Why is there this difference between my form and Django's? How can I make the tag value render correctly in my custom form template?
I have a solution that feels hacky but works.
When instantiating the form, modify the initial state for the tags:
form = YourModelForm(request.POST or None, instance=your_model_instance, initial={
'tags' : edit_string_for_tags(your_model_instance.tags.get_query_set())
})
edit_string_for_tags() and get_query_set() are part of Django Taggit.
Note: You'll need to import edit_string_for_tags(). i.e. from taggit.utils import edit_string_for_tags
I have django form, but in my HTML i added one extra input field (directly added in html page) which i can access it using request.POST.get('extra_field_name') in my django views.
If form.is_valid() is false i can get the form as HTML with the data displayed in the HTML but with empty value for the extra added field( directly added in html page)
How can i get the bounded form data for this newly added extra html field after validation fials.
Please provide your suggestions?
View:
html_added_field = ''
error_added_field = None
if request.method == 'POST':
html_added_field = request.POST.get('extra_field_name')\
if form.is_valid():
pass
else:
error_added_field = _('Error')
context = {'html_added_field':html_added_field,'error_added_field':error_added_field}
HTML:
<input type="text" value="{{ html_added_field }}" />{% if error_added_field %}<div class="error">{{ error_added_field }}</div>{% endif %}
This article by Bennett may help you.
http://www.b-list.org/weblog/2008/nov/09/dynamic-forms/
Briefly, you have to override the __init__ method of your form, adding there the new "extra_field_name". The fields are included in the self.fields list, so doing:
self.fields['extra_field_name'] = forms.CharField(put_here_definitions_for_your_field)
should do the trick.
Honestly the best way would be for your base django form to handle the extra field. Not using extra fields in the html. However if you can't/don't want, as xbello states, in http://www.b-list.org/weblog/2008/nov/09/dynamic-forms/ you have various tricks for handling dynamic fields.
I found more robust to use the form factory method. A function that generates a dynamic form, prepared for more future changes. Still, you have to decide the best approach :-)
I am creating an application to display articles. In my model, I have a TextField that will contain the content of the article.
Now I would like to be able to render another application within my article. Let say I have a poll application and I would like to display a poll in the middle of the article. How can I do that ?
I tried by putting a {% render_poll 42 %} within the post but, as expected, it just display that within the generated page.
Should I create some kind of tag (like let say [poll=42]) and parse it before displaying the rendered html page ? (I use the markdown library, maybe I could extend it.) How can I do that to stay in a nice "django friendly" way ? I want that, when in the admin panel, I can easily insert poll (or other apps) within an article.
You could compile the TextField string as a template. Ie.:
from django.db import models
from django.template import Template, Context
class YourModel(models.Model):
body = models.TextField()
def render_body(self, context=None):
template = Template(self.body)
context = context or {}
context['object'] = self
return template.render(Context(context))
Then in the actual template, you could use {{ your_model.render_body }} rather than {{ your_model.body }}.
Currently, I am writing up a bit of a product-based CMS as my first project.
Here is my question. How can I add additional data (products) to my Product model?
I have added '/admin/products/add' to my urls.py, but I don't really know where to go from there. How would i build both my view and my template? Please keep in mind that I don't really know all that much Python, and i am very new to Django
How can I do this all without using this existing django admin interface.
You will want to wire your URL to the Django create_object generic view, and pass it either "model" (the model you want to create) or "form_class" (a customized ModelForm class). There are a number of other arguments you can also pass to override default behaviors.
Sample URLconf for the simplest case:
from django.conf.urls.defaults import *
from django.views.generic.create_update import create_object
from my_products_app.models import Product
urlpatterns = patterns('',
url(r'^admin/products/add/$', create_object, {'model': Product}))
Your template will get the context variable "form", which you just need to wrap in a <form> tag and add a submit button. The simplest working template (by default should go in "my_products_app/product_form.html"):
<form action="." method="POST">
{{ form }}
<input type="submit" name="submit" value="add">
</form>
Note that your Product model must have a get_absolute_url method, or else you must pass in the post_save_redirect parameter to the view. Otherwise it won't know where to redirect to after save.
This topic is covered in Django tutorials.
Follow the Django tutorial for setting up the "admin" part of an application. This will allow you to modify your database.
Django Admin Setup
Alternatively, you can just connect directly to the database using the standard tools for whatever database type you are using.