'QueryDict'对象没有属性

时间:2015-07-23 09:26:57

标签: django django-queryset attributeerror

我正在尝试将成员分配给组(单元),但我得到'QueryDict'对象在POST上没有属性错误。

如果请求不是POST,则表单将按原样呈现,为我提供组的名称字段(单位),并且使用用户进行多次选择是此部落。但是如果请求是POST,它会给我错误。

我确信此代码存在更多问题,我将非常感谢您的详细解答,因为我是Django和Python的新手。提前谢谢。

models.py

class ClanProfile(models.Model):
    tag = models.CharField(max_length=12, unique=True)
    url = models.SlugField(max_length=12, unique=True, help_text="URL of your clan", db_index=True)
    owner = models.ForeignKey(User)

    members = models.ManyToManyField(User, through='Membership', related_name='clan_members', through_fields=('clan', 'user'))

    def __unicode__(self):
        return self.tag


class Unit(models.Model):
    name = models.CharField(max_length=64)
    clan = models.ForeignKey(ClanProfile)
    members = models.ManyToManyField(User, through='Membership', related_name='unit_members', through_fields=('unit', 'user', 'clan'))
    def __unicode__(self):
        return self.name

class Membership(models.Model):
    user = models.ForeignKey(User)
    clan = models.ForeignKey(ClanProfile)
    unit = models.ForeignKey(Unit, blank=True, null=True)
    date_joined = models.DateField(blank=True, auto_now_add=True)

views.py

@login_required
def AddUnit(request, url):
    clan = get_object_or_404(ClanProfile, url=url)
    if clan.owner != request.user:
        return HttpResponse('<strong>You are not the owner of this clan!</strong>')
    if request.method == 'POST':
        form = AddUnitForm(request.POST, clan)
        if form.is_valid():
            submission = form.save(commit=False)
            submission.clan = clan
            submission.save()
            return HttpResponseRedirect("/%s" % clan.url)
    else:
        form = AddUnitForm(clan)
    return render(request, 'app/add_unit.html', {'form': form})

forms.py

class AddUnitForm(ModelForm):
    def __init__(self, clan, *args, **kwargs):
        super(AddUnitForm, self).__init__(*args, **kwargs)
        self.fields['members'] = forms.ModelMultipleChoiceField(queryset=clan.members, label='Assign members', )
    class Meta:
        model = Unit
        exclude = ['clan']

回溯:

 Environment:


Request Method: POST
Request URL: http://127.0.0.1:8000/41/add-unit/

Django Version: 1.8.3
Python Version: 2.7.10
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'app')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'django.middleware.security.SecurityMiddleware')


Traceback:

    File "D:\django\project\env\lib\site-packages\django\core\handlers\base.py" in get_response
      132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
    File "D:\django\project\env\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
      22.                 return view_func(request, *args, **kwargs)
    File "D:\django\project\app\views.py" in AddUnit
      85.         form = AddUnitForm(request.POST, clan)
    File "D:\django\project\app\forms.py" in __init__
      16.         self.fields['members'] = forms.ModelMultipleChoiceField(queryset=clan.members, label='Assign members', )

    Exception Type: AttributeError at /41/add-unit/
    Exception Value: 'QueryDict' object has no attribute 'members'

1 个答案:

答案 0 :(得分:2)

您已将表单定义为接受clan作为第一个位置arg,但您首先要传递request.POST

应该是:

form = AddUnitForm(clan, request.POST)

请注意,弄乱班级签名是一个非常糟糕的主意;最好将clan作为关键字参数传递,然后从**kwargs弹出。