Home > Net >  How to insert raw html into form when creating a page using django
How to insert raw html into form when creating a page using django

Time:01-08

I want to include things like hyperlinks, quoting, italicized text, etc. into my pages I post on the site I wrote with django but it seems to escape my code. What can I do to add this feature? Has someone else already done something I could just use?

CodePudding user response:

I did this way. Hopefully, it will help you.

suppose you want like this :::

<form action="/your-name/" method="post">
    <label for="your_name">Your name: </label>
    <input id="your_name" type="text" name="your_name" value="{{ current_name }}">
    <input type="submit" value="OK">
</form>

We already know what we want our HTML form to look like. Our starting point for it in Django is this: #forms.py from django import forms

class NameForm(forms.Form):
    your_name = forms.CharField(label='Your name', max_length=100)

The whole form, when rendered for the first time, will look like:

    <label for="your_name">Your name: </label>
<input id="your_name" type="text" name="your_name" maxlength="100" required>

To handle the form we need to instantiate it in the view for the URL where we want it to be published:

from django.http import HttpResponseRedirect
from django.shortcuts import render

from .forms import NameForm

def get_name(request):
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = NameForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            # process the data in form.cleaned_data as required
            # ...
            # redirect to a new URL:
            return HttpResponseRedirect('/thanks/')

    # if a GET (or any other method) we'll create a blank form
    else:
        form = NameForm()

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

We don’t need to do much in our name.html template:

<form action="/your-name/" method="post">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="Submit">
</form>

All the form’s fields and their attributes will be unpacked into HTML markup from that {{ form }} by Django’s template language.

Hopefully, this works or you can follow the official documentation. https://docs.djangoproject.com/en/4.0/topics/forms/

  •  Tags:  
  • Related