我有一个带有models.py的应用程序文件管理器,如下所示:
from django.db import models
from django.contrib.auth.models import User
from fileman.fields import AutoForeignKey
from django.utils.translation import ugettext as _
class Setting(models.Model):
owner = AutoForeignKey(User, unique=True, related_name='fileman_Setting')
root = models.CharField(max_length=250, null=True)
home = models.CharField(max_length=250, null=True)
buffer = models.TextField(blank=True)
class Meta:
permissions = (
("can_fm_list", _("Can look files list")),
("can_fm_add", _("Can upload files")),
("can_fm_rename", _("Can rename files")),
("can_fm_del", _("Can move files to basket")),
("can_fm_destruct", _("Can delete files")),
)
def __unicode__(self):
return unicode(self.owner)
def __init__(self, *args, **kwargs):
super(Setting, self).__init__(*args, **kwargs)
if not self.root:
self.root = None
self.home = None
def writeBuffer(self, data):
self.buffer = data
self.save()
我想在用户注册时为其分配root,home和权限:这就是我在userprofile / views.py中的内容
from fileman.models import Setting
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password1')
newuser = User.objects.create_user(username=username, email='', password=password)
if form.cleaned_data.get('email'):
newuser.email = form.cleaned_data.get('email')
EmailValidation.objects.add(user=newuser, email=newuser.email)
newuser.save()
# Fileman Settings
newuser.fileman_Setting.owner = newuser
newuser.fileman_Setting.root = '/home/aton2/ajunkkil/Django/basedraft/uploads'
print(newuser.fileman_Setting.root)
newuser.fileman_Setting.home = '/home/aton2/ajunkkil/Django/basedraft/uploads/useruploads'
print(newuser.fileman_Setting.home)
newuser.save()
return HttpResponseRedirect('%scomplete/' % request.path_info)
else:
form = RegistrationForm()
template = "userprofile/account/registration.html"
data = { 'form': form, }
return render_to_response(template, data, context_instance=RequestContext(request))
该应用程序在管理员中具有一项功能,允许用户为其中的用户设置根文件夹和主文件夹。但我想让它在用户注册时自动发生。虽然print(newuser.fileman_Setting.root)
是正确的,但我得到了主人很好,但是家和根仍然是'无'。我错过了什么?
FILEMAN / admin.py
from django.contrib import admin
from fileman.models import *
class SettingAdmin(admin.ModelAdmin):
list_display = ('owner', 'root', 'home')
admin.site.register(Setting, SettingAdmin)
答案 0 :(得分:0)
您还需要保存newuser.fileman_Setting
,因为django不会自动保存对模型的更改。
答案 1 :(得分:0)
我不知道AutoForeignKey
做了什么,但假设它类似于标准的ForeignKey,反向fileman_Setting
指的是QuerySet。
ForeignKey是一对多的关系,其中一个是定义FK的一方,而反向关系 - 通过related_name
中指定的名称访问 - 是多个,因此表示为一个QuerySet。因此,不是在单个Setting上设置home和root字段,而是在QuerySet上定义任意属性,然后忽略这些属性。
听起来你可能想要OneToOneField,无论如何。一旦你完成了,那么德米特里说你需要记住保存它。