I wanna use Froala editor (or similar editor) for creating and editing articles in my site. I can create any article with this form/can get data from editor, but i don't know how to insert article data from DB through view function into {{ form }}
of editor in my template. How to do this? Are there other more suitable forms/editors for this case?
forms.py
from froala_editor.widgets import FroalaEditor
class FroalaModelForm(forms.ModelForm):
content = forms.CharField(widget=FroalaEditor)
class Meta:
model = FroalaModel
fields = ('name', 'content')
views.py
def post_froala_form(request):
form = FroalaModelForm(request.POST)
if form.is_valid():
form = form.save(commit=False)
form.name = request.POST['name']
form.content = request.POST['content']
form.save()
return HttpResponseRedirect(reverse('polls:froala_index'))
else:
return render(request, 'polls/froala template.html', {
'form': form
})
froala_template.html
{% load crispy_forms_filters %}
{% load crispy_forms_tags %}
{% block title %}
Froala template
{% endblock %}
{% block content %}
<form action="{% url 'polls:post_froala_form' %}" method="post">
{% csrf_token %}
{{ form.media }}
{{ form|crispy }}
<button type="submit">Send form</button>
</form>
{% endblock content %}
I decided this with Django Forms, indicating in the parameter "instance" a field from the database:
views.py
def question_create_update_form(request, question_id=None):
if question_id:
question = Question.objects.get(id=question_id)
if question.author_name == request.user.username:
form = AddQuestionForm(instance=question)
return render(request, 'polls/add_question.html', {
'title': question.question_title,
'choices': question.choice_set.all(),
'tags': question.tag.all(),
'question_id': question_id,
'form': form
})
else:
return HttpResponseRedirect(reverse('polls:create_question'))
else:
return render(request, 'polls/add_question.html', {
'form': AddQuestionForm
})