Edgar Navasardyan
Edgar Navasardyan

Reputation: 4501

Make Django build contenteditable div for TextField instead of textarea

In my Django 1.10 project, I have a model:

class Contact(models.Model):
    notes = models.TextField()

...and ModelForm:

class ContactForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):    
        super(ContactForm, self).__init__(*args, **kwargs)   
        for field_name, field in self.fields.items():
            field.widget.attrs['class'] = 'form-control input-sm plain'
            if field.required == True: 
                field.widget.attrs['required'] = ''

    class Meta:
        model = Contact
        fields = ('notes',)

I have two questions regarding this:

  1. Can I make Django render the notes field as div with contenteditable=true rather than textarea?
  2. If yes, how do I automate the form.save() method?

The second question is a bit vague, so I would be grateful for a hint regarding the first question. I have read through the doc, but couldn't find relevant section :(

Upvotes: 5

Views: 1698

Answers (2)

Antwane
Antwane

Reputation: 22618

Question 1: Render a field with a specific HTML tag

In this case, <div contenteditable="true">...</div>

You can customize the widget used to render a form field. Basically, when you declare the field, you have to pass the argument widget=TheWidgetClass. Django has a lot of builtin widgets you can use. But you can also define your own. To know how, you will find many resources on the Internet. Simply search for "django create custom widget" on a search engine, or on SO. Possible answer: Django: How to build a custom form widget?

Since Django doesn't provide any official documentation on how to create custom widget, the smartest way would be to create a class inheriting Django's TextArea and using a custom html template based on original one.

Question 2: Automate form.save() method with such a custom widget

Basically, you have to make sure the value of the div tag is sent with other inputs values to the target view of your form, in POST data. In other words, you have to make sure the content of the div acts like the content of any form field. Maybe this SO question can help you: one solution could be using JavaScript to copy the content of your div to a hidden textarea tag in the form when the user click on submit button.

Good luck ;)

Upvotes: 2

sumitroy
sumitroy

Reputation: 458

First one can be done by using jquery. Since django will load the textarea with id='id_notes'. So after that you can select the element and do whatever you want to.

And in second one you can redefine the save method by writing you own save function in forms.py Here is an example for a url shortener. Save method basically, defines what you want to execute when something is being committed to database.

Upvotes: 0

Related Questions