我正在开发一个多租户应用程序,其中一些用户可以定义自己的数据字段(通过管理员)以收集表单中的其他数据并报告数据.后一位使JSONField不是一个很好的选择,所以我有以下解决方案:
class CustomDataField(models.Model):
"""
Abstract specification for arbitrary data fields.
Not used for holding data itself, but metadata about the fields.
"""
site = models.ForeignKey(Site, default=settings.SITE_ID)
name = models.CharField(max_length=64)
class Meta:
abstract = True
class CustomDataValue(models.Model):
"""
Abstract specification for arbitrary data.
"""
value = models.CharField(max_length=1024)
class Meta:
abstract = True
Run Code Online (Sandbox Code Playgroud)
请注意CustomDataField如何具有ForeignKey to Site - 每个站点将具有一组不同的自定义数据字段,但使用相同的数据库.然后,各种具体数据字段可以定义为:
class UserCustomDataField(CustomDataField):
pass
class UserCustomDataValue(CustomDataValue):
custom_field = models.ForeignKey(UserCustomDataField)
user = models.ForeignKey(User, related_name='custom_data')
class Meta:
unique_together=(('user','custom_field'),)
Run Code Online (Sandbox Code Playgroud)
这导致以下用途:
custom_field = UserCustomDataField.objects.create(name='zodiac', site=my_site) #probably created …Run Code Online (Sandbox Code Playgroud) 我有一个Django模型的自定义管理器.我似乎无法在这里捕获DoesNotExist异常.我知道如何在模型中做到这一点,但它在这里不起作用:
class TaskManager(models.Manager):
def task_depend_tree(self, *args, **kwargs):
if "id" in kwargs:
try:
task = self.get(id=kwargs["id"])
except DoesNotExist:
raise Http404
Run Code Online (Sandbox Code Playgroud)
Get_object_or_404也不起作用.这有什么不对?
我想覆盖自定义对象模型管理器,只返回特定用户创建的对象.管理员用户仍应使用对象模型管理器返回所有对象.
现在我找到了一种可行的方法.他们建议创建自己的中间件,如下所示:
#### myproject/middleware/threadlocals.py
try:
from threading import local
except ImportError:
# Python 2.3 compatibility
from django.utils._threading_local import local
_thread_locals = local()
def get_current_user():
return getattr(_thread_locals, 'user', None)
class ThreadLocals(object):
"""Middleware that gets various objects from the
request object and saves them in thread local storage."""
def process_request(self, request):
_thread_locals.user = getattr(request, 'user', None)
#### end
Run Code Online (Sandbox Code Playgroud)
在自定义管理器中,您可以调用该get_current_user()方法仅返回特定用户创建的对象.
class UserContactManager(models.Manager):
def get_query_set(self):
return super(UserContactManager, self).get_query_set().filter(creator=get_current_user())
Run Code Online (Sandbox Code Playgroud)
这是一个很好的方法来处理这个用例吗?这会有用吗?或者这就像"使用大锤破解坚果"?;-)
只是使用:
Contact.objects.filter(created_by= user)
Run Code Online (Sandbox Code Playgroud)
在每个视图中看起来都不是很整洁.
经过一段时间的测试后,这种方法表现得相当奇怪,通过这种方法,您可以将全局状态与当前请求混合在一起.
使用下面介绍的方法.它非常简单,无需乱搞中间件. …
添加profile_picture字段后出现以下错误:
TypeError: create_superuser() missing 1 required positional argument: 'profile_picture'
Run Code Online (Sandbox Code Playgroud)
此 profile_picture 字段是设置为“Null = True”的“ImageField”。
我曾尝试以下:def create_user(...., profile_picture=None, ....)。它没有用。
并且当我创建从那里超级用户只发生在命令提示的误差。
这是我的models.py
from django.db import models
from django.contrib.auth.models import BaseUserManager, AbstractBaseUser
class UserManager(BaseUserManager):
def create_user(self, email, full_name, profile_picture=None, gender=None, password=None, is_admin=False, is_staff=False, is_active=True):
if not email:
raise ValueError("User must have an email")
if not password:
raise ValueError("User must have a password")
if not full_name:
raise ValueError("User must have a full name")
user = self.model(
email=self.normalize_email(email)
)
user.full_name …Run Code Online (Sandbox Code Playgroud) python django typeerror django-custom-manager django-custom-user
我一直在尝试使用成功创建的超级用户登录django管理面板几个小时,但无法获得正确的用户名/ pw组合.
我希望用户只使用他们的电子邮件作为用户名.我也尽力在这里复制Django文档中的示例.我删除了迁移,sycndb,除了登录管理面板外,一切正常.
相关代码:来自models.py:
from django.db import models
from django.forms import ModelForm
from django.contrib.auth.models import BaseUserManager, AbstractBaseUser
class UserManager(BaseUserManager):
def create_user(self, email, password=None):
"""
Creates and saves a User with the given email
"""
if not email:
raise ValueError('Users must have an email address')
user = self.model(
email=UserManager.normalize_email(email),
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, password):
"""
Creates and saves a superuser with the given email, date of
birth and password.
"""
user = self.create_user(email, …Run Code Online (Sandbox Code Playgroud) 所以我正在制作费用表django应用程序而且我一直试图渲染所有输入费用的总和.
我已经创建了一个自定义管理器来计算总和:
class ExpenseManager(models.Manager):
def price_sum(self):
return super(ExpenseManager, self).aggregate(total_price = Sum('price'))['total_price']
Run Code Online (Sandbox Code Playgroud)
并将其添加到我的模型中:
class Expense(models.Model):
...
objects = models.Manager()
price_object = ExpenseManager()
...
Run Code Online (Sandbox Code Playgroud)
我知道我的经理是有效的,因为当我在shell中执行它时,我得到了正确的费用总额 - 即我放入Expense.price_object.price_sum()并且我回来了Decimal('254.77')- 但是当我尝试将其添加到我的模板中时它只显示空白.
我尝试过几种不同的方式输入我的变量,但没有一种方法可行,例如:
{{price_object.price_sum}}
Run Code Online (Sandbox Code Playgroud)
要么
{{expense.price_object.price_sum}}
Run Code Online (Sandbox Code Playgroud)
或者我变得绝望......
{% for p in expense.price_object %} {{p.price_sum}} {% endfor %}
Run Code Online (Sandbox Code Playgroud)
要么
{% for p in expense.price_object.price_sum %} {{p}} {% endfor %}
Run Code Online (Sandbox Code Playgroud)
但是,当我加载页面时,什么都没有显示出来.有人可以帮忙吗?
我使用的是 Django 1.10.3,在迁移步骤中,当我使用 RunPython() 调用自定义管理器方法时遇到错误。有什么想法我做错了吗?
错误消息是: AttributeError: 'Manager' 对象没有属性 'current_event'
我的模特和经理:
class EventManager(models.Manager):
use_in_migrations = True
def current_event(self):
try:
the_event = self.filter(
event_date__gte=date.today()
).earliest(
field_name='event_date'
)
except ObjectDoesNotExist:
the_event = None
return the_event
class Event(models.Model):
event_date = models.DateField()
objects = EventManager()
Run Code Online (Sandbox Code Playgroud)
我的迁移:
def update_ratings_event(apps, schema_editor):
Rating = apps.get_model('league', 'Rating')
Event = apps.get_model('league', 'Event')
recent_event = Event.objects.current_event()
for a_rating in Rating.objects.all():
a_rating.event = recent_event
a_rating.save()
class Migration(migrations.Migration):
dependencies = [
('league', '0009_auto_20170401_1106'),
]
operations = [
migrations.RunPython(update_ratings_event),
]
Run Code Online (Sandbox Code Playgroud)
这是回溯:
File "manage.py", …Run Code Online (Sandbox Code Playgroud) 我有几个模型通过外键关系相互连接。
这种层次结构中的主要层次结构包含一个所有者字段。
我想为所有这些模型创建一个自定义管理器,根据调用它的模型更改返回的查询集。
我知道经理可以访问self.model以获取它所附加的模型。
Class Main(models.Model)
owner=models.ForeignKey (User)
owned = OwnedManager()
Class Second(models.Model)
main=models.ForeignKey('Main')
owned = OwnedManager()
Class Third(models.Model)
second=models.ForeignKey('Second')
owned = OwnedManager()
Run Code Online (Sandbox Code Playgroud)
我希望我的自定义管理器具有这种行为:
class OwnedManager(models.Manager):
def get_owned_objs(self, owner):
if self.model == 'Main': # WRONG: How do I get the model name?
owned_main = self.filter(owner=owner)
return owned_main
elif self.model == 'Second':
owned_second = self.filter(main__owner=owner)
return owned_second
else:
owned_third = self.filter(second__main__owner=owner)
return owned_third
Run Code Online (Sandbox Code Playgroud)
为了以一致的方式在不同的模型中调用它,如下所示:
main_object.owned.get_owned_objs(owner=user1) # of the Model Main
second_object.owned.get_owned_objs(owner=user1) # of …Run Code Online (Sandbox Code Playgroud) 当我尝试使用终端创建新的超级用户时出现以下错误。
TypeError: create_superuser() missing 3 required positional arguments: 'first_name', 'last_name', and 'location'
Run Code Online (Sandbox Code Playgroud)
我在下面的评论中关注了另一个 stackoverflow 页面。在该页面中,它坚持创建一个 create_superuser 函数,但user.save(using=self._db)
此代码仍有错误,
如何使用“first_name”、“last_name”和“location”而不向它们提供任何默认值。
first_name 、 last_name 和 location 是 max_length = 30 的 CharField,并且可以有空白值。
在此自定义用户模型中,用户名被替换为 mobile_no,使其在 User 类中具有唯一性。
模型.py
from django.db import models
from django.contrib.auth.models import (
AbstractBaseUser, BaseUserManager,PermissionsMixin
)
class UserManager(BaseUserManager):
# All required field must be passed below as argument
def create_user(self, mobile_no, role, email, first_name, last_name, location, password=None, is_active=True,is_staff=False, is_admin= False):
if not mobile_no:
raise ValueError("User must have an Mobile …Run Code Online (Sandbox Code Playgroud) python django typeerror django-custom-manager django-custom-user