[英]Extending Django User Model and Accessing it
I extended the User model in Django with a model called Client. 我使用名为Client的模型在Django中扩展了User模型。
It looks like this: 它看起来像这样:
@python_2_unicode_compatible
class Client(models.Model):
user = models.OneToOneField(User)
company = models.CharField(max_length=100)
def __str__(self):
return self.company
class Meta:
verbose_name_plural = _("Clients")
verbose_name = _("Client")
permissions = (
("can_upload", _("Can upload files.")),
("can_access_uploads", _("Can access upload dashboard.")),
("is_client", _("Is a client.")),
)
However, I cannot figure out how to access this model through the current user in a view for example: 但是,我无法弄清楚如何通过视图中的当前用户访问此模型,例如:
def dashboard(request):
current_user = request.user
current_client = Client.objects.filter(user__icontains=current_user)
files = ClientUpload.objects.filter(client__icontains=current_client)
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
new_file = UploadFile(file = request.FILES['file'])
new_file.save()
return HttpResponsePermanentRedirect('/dashboard/')
else:
form = UploadFileForm()
data = {'form': form, 'client': current_client, 'files': files}
return render_to_response('dashboard.html', data, context_instance=RequestContext(request))
ClientUpload Model: ClientUpload模型:
@python_2_unicode_compatible
class ClientUpload(models.Model):
client = models.OneToOneField(Client)
def generate_filename(self, filename):
url = "uploads/%s/%s" % (self.client.company, filename)
return url
file_upload = models.FileField(upload_to=generate_filename)
def __str__(self):
return self.client.company
class Meta:
verbose_name_plural = _("Client Uploads")
verbose_name = _("Client Upload")
I get the current user with request.user
but I can't figure out how to get the client related to that user. 我通过
request.user
获取当前用户,但我无法弄清楚如何让客户端与该用户相关。 When I load the dashboard view I get the error: 当我加载仪表板视图时,我收到错误:
"Related Field got invalid lookup: icontains" “相关字段无效查找:icontains”
How can I access the client model associated with a user when I extend the user model in this fashion according to the docs? 当我根据文档以这种方式扩展用户模型时,如何访问与用户关联的客户端模型?
Thanks for any help or suggestions. 感谢您的任何帮助或建议。
您可以像这样访问给定User
的Client
对象:
client = request.user.client
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.