小编给大家分享一下Django如何实现Admin自动填充当前用户,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!
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)
以上是“Django如何实现Admin自动填充当前用户”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。