我的模特用户可以创建步枪,这支步枪显然与用户有关。
class Gun(ImageModel):
user = models.ForeignKey(User)
...
...
...
我有另一个依赖于此的模型并且需要使用用户步枪,但是当用户添加记录时我只想显示他的步枪。
mt模型如下所示
class Trophies(ImageModel):
used_his = models.ForeignKey(Gun)
我的表格如下
from django.forms import ModelForm
from django import forms
from models import Trophies
from gunsafe.models import Gun
from django.contrib.auth.models import User
class TrophiesForm(request.user, ModelForm):
used_his = forms.ModelMultipleChoiceField(queryset=Gun.objects.filter(user__id=1))
def __init__(self, user, *args, **kwargs):
super(TrophiesForm, self).__init__(*args, **kwargs)
self.fields['used_his'].queryset = User.objects.filter(pk = user)
我想知道如何获取当前登录的用户ID而不是user__id=1
以下是观点。
def edit(request, trophy_id, template_name='trophies/edit.html'):
trophy = Trophies.objects.get(pk=trophy_id)
if request.method == 'POST':
form = TrophiesForm(request.POST, request.FILES, instance=trophy)
if form.is_valid():
newform = form.save(commit=False)
newform.user = request.user
newform.save()
...
...
答案 0 :(得分:10)
我认为您可以通过覆盖表单的__init__()
方法,传入User
的实例并使用该用户过滤queryset
来实现此目的。像这样:
class TrophiesForm(ModelForm):
used_his = forms.ModelMultipleChoiceField(queryset=Gun.objects.filter(user__id=1))
def __init__(self, user, *args, **kwargs):
super(TrophiesForm, self).__init__(*args, **kwargs)
self.fields['used_his'].queryset = User.objects.filter(pk = user.id)
在您的视图中,您可以传入User
的相应(当前登录)实例。
def my_trophies(request, *args, **kwargs):
user = request.user
form = TrophiesForm(user)
...
答案 1 :(得分:5)
Manoj提交的另一个角度......
使用kwarg传递用户数据,以免弄乱方法签名,因为它期望request.POST作为第一个参数。更好的惯例如下:
class TrophiesForm(ModelForm):
def __init__(self, *args, **kwargs):
#using kwargs
user = kwargs.pop('user', None)
super(TrophiesForm, self).__init__(*args, **kwargs)
self.fields['used_his'].queryset = User.objects.filter(pk = user.id)
现在在调用中,这更明确,遵循更好的签名约定
form = TrophiesForm(request.POST, request.FILES, user=request.user)
您也可以使用实例:(在获取实例obj之前注意super)
class TrophiesForm(ModelForm):
def __init__(self, *args, **kwargs):
super(SubmissionUploadForm, self).__init__(*args, **kwargs)
user = self.instance.user
self.fields['used_his'].queryset = User.objects.filter(pk = user.id)
然后,您可以调用views.py,如下所示:
form = TrophiesForm(instance=*MyModel*(user=request.user))