我试图添加功能来编辑和删除帖子。 我用Google搜索,似乎有两个选项,创建像这里的函数,How do I edit and delete data in Django?或只使用像这里的通用编辑视图:Create, Update and Delete in Django我个人想要使用通用编辑视图,但它&#39 ;有点难以理解,而不仅仅是创建函数。如果您可以帮助我使用通用编辑视图,我将不胜感激。
def post(request, slug):
single_post = get_object_or_404(Post, slug=slug)
single_post.views += 1 # increment the number of views
single_post.save() # and save it
t = loader.get_template('main/post.html')
context_dict = {
'single_post': single_post,
}
c = Context(context_dict)
return HttpResponse(t.render(c))
def add_post(request):
context = RequestContext(request)
if request.method == 'POST':
form = PostForm(request.POST, request.FILES)
if form.is_valid(): # is the form valid?
form.save(commit=True) # yes? save to database
return redirect(index)
else:
print form.errors # no? display errors to end user
else:
form = PostForm()
return render_to_response('main/add_post.html', {'form': form}, context)
class Post(models.Model):
category = models.ForeignKey(Category)
created_at = models.DateTimeField(auto_now_add = True)
title = models.CharField(max_length = 100)
content = models.TextField()
url = models.URLField(max_length=250, blank=True)
ups = models.IntegerField(default=0)
down = models.IntegerField(default=0)
score = models.IntegerField(default=0)
views = models.IntegerField(default=0)
image = models.ImageField(upload_to="images",blank=True, null=True)
slug = models.CharField(max_length=100, unique=True)
def save(self, *args, **kwargs):
self.slug = uuslug(self.title, instance=self, max_length=100)
super(Post, self).save(*args, **kwargs)
def __unicode__(self):
return self.title
class PostForm(forms.ModelForm):
title = forms.CharField(max_length=128, help_text="plz enter")
views = forms.IntegerField(widget=forms.HiddenInput(), initial=0)
class Meta:
model = Post
fields = ['title', 'content', 'image', 'views', 'category']
答案 0 :(得分:4)
以下是每个
的示例在views.py
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.http import HttpResponse, HttpResponseRedirect
from django.core.urlresolvers import reverse
from .models import *
from .forms import *
class PostCreateView(CreateView):
model = Post
form_class = PostForm
template_name = 'form.html'
def form_valid(self, form):
self.object = form.save(commit=False)
# any manual settings go here
self.object.save()
return HttpResponseRedirect(self.object.get_absolute_url())
@method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
return super(PostCreateView, self).dispatch(request, *args, **kwargs)
class PostUpdateView(UpdateView):
model = Post
form_class = PostForm
template_name = 'form.html'
def form_valid(self, form):
self.object = form.save(commit=False)
# Any manual settings go here
self.object.save()
return HttpResponseRedirect(self.object.get_absolute_url())
@method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
return super(PostUpdateView, self).dispatch(request, *args, **kwargs)
class PostDeleteView(DeleteView):
model = Post
def get_success_url(self):
return reverse('post-index') # Or whatever you need
@method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
return super(PostDeleteView, self).dispatch(request, *args, **kwargs)
urls.py
上的,你需要像
这样的东西from django.conf.urls import patterns, url
from .views import *
urlpatterns = patterns('',
url(r'^add/$', PostCreateView.as_view(), name='post-add'),
url(r'^(?P<pk>\d+)/edit/$', PostUpdateView.as_view(), name='post-edit'),
url(r'^(?P<pk>\d+)/delete/$', PostDeleteView.as_view(), name='post-delete'),
)
您需要一个post_confirm_delete.html模板,例如:
<form action="" method="post">{% csrf_token %}
<p>Are you sure you want to delete "{{ object }}"?</p>
<input type="submit" value="Confirm" />
</form>
希望这就是你要找的东西。
以下是有关该主题的完整教程
http://www.onespacemedia.com/news/2014/feb/5/getting-started-generic-class-based-views-django/