Django Как безопасно отобразить ссылку из формы ввода пользователя
У меня есть модель (посты), связанная с формой, которая при использовании определенного символа создает ссылку на другую часть веб-приложения. Пользователь может ввести несколько таких символов/ссылки на различные области веб-страницы в одном сообщении, затем я хочу отобразить все сообщения пользователя в виде списка, переходя по модели, хранящей ссылку. Однако, как я могу сделать это, сохраняя безопасность? Я не хочу, чтобы пользователь мог ввести HTML и он был отображен.
Например:
- User enters form information:
"Hello this is a @test and @about is a test too"
- User selects submit button and background magic to get the words test and about and convert them into links to take the user to the test and about pages in the web application.
- Display all of the inputs/posts that have been created:
"Hello this is @test and @about is a test too"
Я знаю, что могу использовать тег safe
и просто сохранить HTML-ссылку в модели и вызывать ее как обычно, но поскольку она вводится пользователем, я не хочу позволить ему создавать HTML внутри формы ввода. Как я могу безопасно достичь желаемого результата?
Примерно то, что у меня есть сейчас: views.py
def index(request):
if request.method == "POST":
post_form = PostForm(request.POST, request.FILES)
if post_form.is_valid():
# TODO Add background magic here
post_form.save()
messages.success(request, ('Your post was successfully added!'))
else:
messages.error(request, 'Error saving form')
return redirect("/posts")
post_form = PostForm()
posts = Post.objects.all()
return render(request=request, template_name="posts/page.html", context={'post_form':post_form, 'posts':posts})
page.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Testing</title>
</head>
<body>
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ post_form }}
<button class="btn btn-primary my-4" type="submit">Submit</button>
</form>
{% for post in posts %}
<p>{{post.id}}</p>
<p>{{post.post}}</p>
{% endfor %}
</body>
</html>