脚本专栏 
首页 > 脚本专栏 > 浏览文章

Django 实现Admin自动填充当前用户的示例代码

(编辑:jimmy 日期: 2024/11/20 浏览:3 次 )

model.py

import datetime

from django.contrib.auth.models import User
from django.db import models


class Entry(models.Model):
  title = models.CharField(max_length=250)
  slug = models.SlugField()
  pub_date = models.DateTimeField(default=datetime.datetime.now)
  author = models.ForeignKey(User, related_name='entries')
  summary = models.TextField(blank=True)
  body = models.TextField()

  class Meta:
    get_latest_by = 'pub_date'
    ordering = ('-pub_date',)
    verbose_name_plural = 'entries'

  def __unicode__(self):
    return self.title

  def get_absolute_url(self):
    return "/weblog/%s/%s/" % (self.pub_date.strftime("%Y/%b/%d"),
                  self.slug)

admin.py

from django.contrib import admin

from blog.models import Entry


class EntryAdmin(admin.ModelAdmin):
  exclude = ('author',)
  list_display = ('title', 'pub_date', 'author')
  prepopulated_fields = { 'slug': ['title'] }

  def has_change_permission(self, request, obj=None):
    has_class_permission = super(EntryAdmin, self).has_change_permission(request, obj)
    if not has_class_permission:
      return False
    if obj is not None and not request.user.is_superuser and request.user.id != obj.author.id:
      return False
    return True

  def queryset(self, request):
    if request.user.is_superuser:
      return Entry.objects.all()
    return Entry.objects.filter(author=request.user)

  def save_model(self, request, obj, form, change):
    if not change:
      obj.author = request.user
    obj.save()

admin.site.register(Entry, EntryAdmin)

参考链接:https://www.b-list.org/weblog/2008/dec/24/admin/

以上这篇Django 实现Admin自动填充当前用户的示例代码就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

上一篇:Django自定义用户表+自定义admin后台中的字段实例
下一篇:Django 创建后台,配置sqlite3教程
友情链接:杰晶网络 DDR爱好者之家 南强小屋 黑松山资源网 白云城资源网 SiteMap