您好,登錄后才能下訂單哦!
小編給大家分享一下Django如何實(shí)現(xiàn)Admin自動(dòng)填充當(dāng)前用戶,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
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如何實(shí)現(xiàn)Admin自動(dòng)填充當(dāng)前用戶”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。