Django Template render dictionary values into html form using Function Based View -


summary

using django 1.8, i'm trying make function based view renders html page allows me update contents of object. i'm able work using form.as_p shown in documentation here, can't these values inside html <input> value.

issue

the issue first word appears , rest of text cut off (e.g. html input tag, value of 'hello world will' gets turned 'hello')

model.py

class questions(model.model):     title = models.charfield(max_length=512, null=false, blank=false) 

forms.py

class questionsform(forms.modelform):     class meta:         model = questions         fields = ('title', ) 

views.py

def advice_update(request, pk)     question_results = questions.object.get(id=pk)     advice_form = questionsform(request.post or none, instance=question_results)     ...     return render(request, 'advice/advice_update.html', {'advice_form': advice_form, 'question_results': question_results,}) 

advice_update.html

<form method='post' action=''>{% csrf_token %}  # method 1 - code works , renders form paragraphs enclosed # want more control {{ advice_form.as_p }}  # method 2 - when try value itself, works {{ advice_form.instance.title }}  # e.g. 'hello world' {{ question_results.title }}  # e.g. 'hello world'  # method 3 - when try put text inside 'value' tag in 'input',  # text gets cut off , first word appears in input # when @ console, see rest of text in there. <input id="id_title" type="text" name="title" class="form-control" value={{ question_results.title }}> 

i tried few things adding autoescape , safe tags, when use method 3, value inside tag of advice.html cuts off when there's space (e.g. 'hello world' turns 'hello').

first, don't need set null=false, blank=false on title field there default.

it looks main issue you're having adding bootstrap css class form element, can accomplish couple of different ways. note value attribute missing quotes around it.

the first way add appropriate classing widget python side of form:

class questionsform(forms.modelform):     class meta:         model = questions         fields = ('title', )          def __init__(self, *args, **kwargs):             super(questionsform, self).__init__(*args, **kwargs)             self.fields['title'].widget.attrs['class'] = 'form-control' 

however, gets tedious when you're dealing lot of form fields. so, use django-widget-tweaks instead add these @ template level:

{{ form.title|add_class:"form-control" }} 

which find lot easier deal with. way don't have render field hand. sure handle case if there's no matching question in view:

question = get_object_or_404(question, id=pk) 

Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -