0

I wish to assign a value from variable word in my view function one_label to the form field label in my template. I've seen some solutions with javascript but I'm not sure how to use them with the form field in the template?

<script type="text/javascript"> 
   var myVar = "{{someDjangoVariable}}"
</script>

in models

class Labels(models.Model):
   label = models.CharField()

in forms

class LabelForm(forms.Form):

 label = forms.CharField(required = False)

in views

def one_label(request, postID):
   one_label = Labels.objects.get(id=postID
   if request.method =='POST':
      form = LabelForm(request.POST)
      if form.is_valid():


         word = "something"
      else:
        form = LabelForm()
      c = {"form"=form, "one_label"=one_label, "word"=word  }
      c.update(csrf(request))
      render(response,'mytemplate.html', c)

in template

 <form action="" method="post">{% csrf_token %}

      {{ form.as_p}}

  # assign value in var "word" in views to form field "label"

 # something like    {{ form.label}}:{{ word}}

 </form>
2
  • Is {{ word }} something that comes from the views context or something else? Commented May 19, 2015 at 12:41
  • its value comes from a separate python function that's called in the view function one_label Commented May 19, 2015 at 12:42

1 Answer 1

2

First, there is a syntax error in your views.py, at least, or this is a syntax totally unknown to me. Context is a Python dictionary that could be declared as:

c = {'form': form, 'one_label': one_label, 'word': word}

I would strongly recommend you to get a grip on a good IDE, it will very much help you with syntax.

Regarding the form rendering, I would then recommend you to expand the form field rendering by replacing {{ form }} with something like:

{{ form.non_field_errors }}
<div class="fieldWrapper">
    {{ form.label.errors }}
    <label for="{{ form.label.id_for_label }}">{{ word }}</label>
    {{ form.label }}
</div>

See also Django documentation: Rendering fields manually

About assigning a value within a template, you could use the {% with %} tag although it seems kind of irrelevant to me for your particular problem.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.