具有 ImageField 属性的 Django UpdateView

Django UpdateView with ImageField attribute

我在制作 UpdateView 时遇到了问题 Class.I 能够在添加 imageField 之前不添加任何表单的情况下执行 createView 和 UpdateView。但是现在我有 imageField,这会产生问题。幸运的是,我能够执行 createView 并且它工作正常。

以下是我的 CreateView 代码

class CreatePostView(FormView):
    form_class = PostForm
    template_name = 'edit_post.html'

    def get_success_url(self):
        return reverse('post-list')
    def form_valid(self, form):
        form.save(commit=True)
        # messages.success(self.request, 'File uploaded!')
        return super(CreatePostView, self).form_valid(form)
    def get_context_data(self, **kwargs):
        context = super(CreatePostView, self).get_context_data(**kwargs)
        context['action'] = reverse('post-new')
        return context

但是,我尝试执行 UpdateView(ViewForm)。以下是我的代码:

class UpdatePostView(SingleObjectMixin,FormView):
model = Post
form_class = PostForm
tempate_name = 'edit_post.html'

# fields = ['title', 'description','content','published','upvote','downvote','image','thumbImage']

def get_success_url(self):
    return reverse('post-list')
def form_valid(self, form):
    form.save(commit=True)
    # messages.success(self.request, 'File uploaded!')
    return super(UpdatePostView, self).form_valid(form)

def get_context_data(self, **kwargs):
    context = super(UpdatePostView, self).get_context_data(**kwargs)
    context['action'] = reverse('post-edit',
                                kwargs={'pk': self.get_object().id})
    return context

当我尝试 运行 updateView 时,出现以下错误:

AttributeError at /posts/edit/23/

'UpdatePostView' object has no attribute 'get_object'

Request Method: GET Request URL: http://localhost:8000/posts/edit/23/ Django Version: 1.8.2 Exception Type: AttributeError Exception Value:

'UpdatePostView' object has no attribute 'get_object'

Exception Location: /home/PostFunctions/mysite/post/views.py in get_context_data, line 72 Python Executable: /usr/bin/python Python Version: 2.7.6

以下是我的url.py:

#ex : /posts/edit/3/

url(r'^edit/(?P<pk>\d+)/$', post.views.UpdatePostView.as_view(),
    name='post-edit',),

我有一个用 ImageField 更新模型的表单。 我确实为我的模型扩展了一个 ModelForm(我想这对你来说是 PostForm)。

但是我的 CustomUpdateView 从 Django 通用视图扩展了 UpdateView。

from django.views.generic.edit import UpdateView
from django.shortcuts import get_object_or_404


class CustomUpdateView(UpdateView):
    template_name = 'some_template.html'
    form_class = CustomModelForm
    success_url = '/some/url'

    def get_object(self): #and you have to override a get_object method
        return get_object_or_404(YourModel, id=self.request.GET.get('pk'))

你只需要定义一个get_object方法,update view就会用form中的值更新对象,但是它需要获取你想要更新的对象。

get_object_or_404() 的工作方式类似于模型上的 get() 函数,因此请将 id 替换为您的 field_id.

的名称

希望对您有所帮助