我在Django model class link
编写了自定义保存方法。
我已添加此方法,以便如果我使用管理面板输入数据它将被执行,我不必手动输入该字段的数据,但现在当我从管理面板输入数据时它仍然要求我输入数据但然后它会简单地覆盖我的条目。这是任何方式它都不允许从管理面板输入该特定值。
import uuid
import base64
import datetime
from django.db import models
from django.contrib import admin
#------------------------------------------------------------------------------
def _generateShortUrl():
"""
This function will generate base64 encoded id
"""
return base64.urlsafe_b64encode(uuid.uuid1().bytes)[:6]
class link(models.Model):
"""
This is a link class
"""
link = models.URLField() # To store user entered URL
hits = models.IntegerField(default=0) # How many hits for particular URL
last_used = models.DateTimeField(auto_now=True) # When URL is last used
short_url = models.CharField(max_length=6,unique=True) # base64 URL encoded id
def linkValidate(self):
timediff = datetime.datetime.now() - self.last_used
return timediff.min
def save(self, *args, **kwargs):
"""
Custom Save method for link model
"""
self.short_url = _generateShortUrl()
super(link, self).save(*args, **kwargs)
class user_info(models.Model):
"""
This is a user_info class
"""
user_agent = models.TextField() # Stores user_agent name used by user
user_ip = models.ManyToManyField(link) # Stores user's IP
def userIP(self):
"""Method to return tags related to store"""
return ','.join([t.link for t in self.link.all()])
#------------------------------------------------------------------------------
class linkAdmin(admin.ModelAdmin):
"""
link admin class
"""
list_display = ('link','hits','short_url','last_used',
'linkValidate')
ordering = ('hits',)
class userInfoAdmin(admin.ModelAdmin):
"""
user_info admin class
"""
list_display = ('user_agent','userIP')
#------------------------------------------------------------------------------
admin.site.register(link,linkAdmin)
admin.site.register(user_info,userInfoAdmin)
答案 0 :(得分:2)
你需要告诉你的模特& ModelAdmin不要求那些字段。
https://docs.djangoproject.com/en/1.6/ref/contrib/admin/#django.contrib.admin.ModelAdmin.exclude
答案 1 :(得分:1)
您可以将字段定义更改为:
short_url = models.CharField(max_length=6,unique=True, default=_generateShortUrl)
或更改linkAdmin
添加:
exclude = ('short_url',)
答案 2 :(得分:0)
您应该尝试在创建实例时为shortURL指定值,而不是在存储时指定。