Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (19.9k points)

consider this model on Django:

class My_model(models.Model):

    my_choices = { '1:first' 2:second'}

    myfield1=CharField()

    myfield2=CharField(choices=my_choices)

Then on my form:

class My_form(forms.ModelForm):

    class Meta:

    model = My_model

    fields = ['myfield1', 'myfield2']

My views:

def get_name(request):

    if request.method == 'POST':

        form = My_form(request.POST)

        if form.is_valid():

            return HttpResponseRedirect('/')

    else:

        form = My_form()

    return render(request, 'form/myform.html', {'form': form})

On my template:

{% extends "base.html" %}

{% block content %}

<form action="/tlevels/" method="POST">

{% csrf_token %}

{{ form.as_p }}

<input type="submit" value="Submit">

</form>

{% endblock %}

On my base.html, I will load this template like this:

{% extends "base.html" %}

{% block content %}

{% load crispy_forms_tags %}

<div class="p-3 mb-2 bg-info text-white" style="margin-left:20px; margin-bottom:20px;">Status</div>

<div class="form-row" style="margin-left:20px; margin-bottom:20px; margin-top:20px;">

  <div class="form-group col-md-6 mb-0">

    {{ form.myfield1|as_crispy_field }}

  </div>

  <div class="form-group col-md-6 mb-0">

    {{ form.myfield2|as_crispy_field }}

  </div>

</div>

<input type="submit" class="btn btn-primary" value="Submit" style="margin-left:20px;">

</form>

{% endblock %}

What I want, is to have 2 other different templates, with whatever difference on them, and load them depending on the choice made on the ChoiceField, I guess that one way could be on the view, by adding some kind of conditional, and load a different template (html file).

1 Answer

0 votes
by (25.1k points)

It is possible to use {% include %} with a variable.

def some_view_after_post(request):

    # ... lookup value of myfield2 ...

    return render(request, "path/to/after_post.html", {'myfield2: myfield2})

The in the after_post.html template:

<!-- include a template based on user's choice -->

<div class="user-choice">

{% include myfield2 %}

</div>

You'll want to make sure there is no possible way the user can inject an erroneous choice. For example, make sure the value of myfield2 choice is valid before adding it to the context.

Related questions

0 votes
1 answer
0 votes
1 answer
asked Oct 8, 2019 in Python by Rajesh Malhotra (19.9k points)
0 votes
1 answer
0 votes
1 answer
asked Mar 8, 2021 in Web Technology by Rekha (2.2k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...