2

我正在使用自定义表单应用程序,我想将 ckeditor 集成到其中。它在 Django Admin 表单中工作得很好,但在普通表单中不起作用。

模型.py

from django.db import models
from django.contrib.auth.models import User
from ckeditor.fields import RichTextField

class Post(models.Model):
    text = RichTextField()

    updated = models.DateTimeField(auto_now=True)
    created = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['created']

    def __unicode__(self):
         return self.text

网址.py

from django.conf.urls import patterns, url

urlpatterns = patterns(
    'editor.views',
    url(r'^$', 'home'),
    url(r'^create_post/$', 'create_post'),
    url(r'^delete_post/$', 'delete_post'),
)

视图.py

def home(req):

    tmpl_vars = {
        'all_posts': Post.objects.reverse(),
        'form': PostForm()
    }
    return render(req, 'editor/index.html', tmpl_vars)

def create_post(request):
    if request.method == 'POST':
        post_text = request.POST.get('the_post')
        response_data = {}
        post = Post(text=post_text, author=request.user)
        post.save()
        post_form = Post()

        response_data['result'] = 'Create post successful!'
        response_data['postpk'] = post.pk
        response_data['text'] = post.text
        response_data['created'] = post.created.strftime('%B %d, %Y %I:%M %p')

        return HttpResponse(
            json.dumps(response_data),
            content_type="application/json"
        )

    else:
        return HttpResponse(
            json.dumps({"nothing to see": "this isn't happening"}),
            content_type="application/json"
        )

表格.py

class PostForm(forms.ModelForm):
    text = forms.CharField(widget = CKEditorWidget())
    class Meta:
        model = Post

索引.html

<form method="POST" id="post-form">
        {% csrf_token %}
        <div id="the_post">
            {{ form.media }}
            {{ form.as_p }}
        </div>
        <div id="results"></div>
        <button type="submit">{% trans 'Submit' %}</button>
 </form>

在 django 管理数据中使用 ckeditor 保存,而在自定义表单数据中使用 ckeditor 不会保存在数据库中。请帮忙。

4

2 回答 2

1

您的RichTextField字段被称为text所以当您检查post数据时,您应该检查“文本”输入:

post_text = request.POST.get('text', '')

我也会像这样处理表格:

if request.method == 'POST':
    # Bind data from request.POST into a PostForm
    form = PostForm(request.POST)
    # If data is valid, proceeds to create a new post
    if form.is_valid():
        post = form.save(commit=False)
        post.author = request.user
        post.save()

        response = {
            'msg': 'Create post successful!'
            'id': post.pk,
            'text': post.text,
            'created': post.created.strftime('%B %d, %Y %I:%M %p')
        }

至于将当前用户保存为author. 我会从您的模型中排除该字段。并author在您的视图中更新:

class PostForm(forms.ModelForm):
    [...]

    class Meta:
        model = Post
        exclude = ('author',)
于 2015-03-08T23:46:20.257 回答
0

Here I have done like this. And it is working for me.

forms.py:

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        # exclude = ['author', 'updated', 'created', ]
        fields = ['text']
        widgets = {
            'text': forms.TextInput(
                attrs={'id': 'post-text', 'required': True, 'placeholder': 'Say something...'}
            ),
        } 

views.py:

def create_post(request):
    if request.method == 'POST':
        post_text = request.POST.get('the_post')
        response_data = {}

        post = Post(text=post_text, author=request.user)
        post.save()

        response_data['result'] = 'Create post successful!'
        response_data['postpk'] = post.pk
        response_data['text'] = post.text
        response_data['created'] = post.created.strftime('%B %d, %Y %I:%M %p')
        response_data['author'] = post.author.username

        return HttpResponse(
            json.dumps(response_data),
            content_type="application/json"
        )
    else:
        return HttpResponse(
            json.dumps({"nothing to see": "this isn't happening"}),
            content_type="application/json"
        )

index.html:

<div>
    <div>
        <form method="POST" id="post-form">
            {% csrf_token %}
            <div id="the_post">
                {{ form.text }}
            </div>
            <div id="results"></div>
            <input type="submit" value="Post">
        </form>
    </div>
</div>
于 2015-03-31T07:08:27.257 回答