Reputation: 147
I am having trouble in making UpdateView Class.I was able to do createView and UpdateView without adding any form before adding up the imageField. But now I have imageField, which is creating problem. Fortunately, I am able to do createView and its working fine.
Following is my code for 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
However, I tried to do UpdateView(ViewForm). Following is my code :
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
When I try to run the updateView, its giving me following error:
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
Following is my url.py :
#ex : /posts/edit/3/
url(r'^edit/(?P<pk>\d+)/$', post.views.UpdatePostView.as_view(),
name='post-edit',),
Upvotes: 3
Views: 2548
Reputation: 2458
I have a form to update Model with ImageField. I do extend a ModelForm for my model (which is PostForm for you I guess).
But my CustomUpdateView extend UpdateView, from django generic view.
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'))
You just have to define a get_object method and update view will update the object with value in form, but it needs to get the object you want to update.
get_object_or_404()
works like a get()
function on a Model, so replace id by the name of your field_id.
Hope it helps
Upvotes: 2