Django:无法保存表单(ModelForm通过request.user过滤ForeignKey选择) [英] Django: saving the Form does not work (The ModelForm Filters the ForeignKey choices by request.user)

查看:76
本文介绍了Django:无法保存表单(ModelForm通过request.user过滤ForeignKey选择)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下代码设法过滤了 request.user的外键选择 Context.name。
首先,我定义了模型。

I Managed to Filter the ForeignKey choices "Context.name" by "request.user" with the Code Below. First, I defined the Models.

models.py

class Extension(models.Model):
   username = models.CharField(primary_key=True, max_length=200, help_text='')
   callerid = models.CharField(max_length=200, help_text='')
   extension = models.CharField(max_length=3, help_text='')
   firstname = models.CharField(max_length=200, help_text='')
   lastname = models.CharField(max_length=200, help_text='')
   password = models.CharField(max_length=200, help_text='')
   context = models.ForeignKey('Context', on_delete=models.SET_NULL, null=True)
   def get_absolute_url(self):
       return reverse('extension-detail', args=[str(self.username)])
   def my_get_absolute_url(self):
       return reverse('my-extension-detail', args=[str(self.username)])
   def __str__(self):
       return self.username

class Context(models.Model):
   name = models.CharField(primary_key=True, max_length=200, help_text='')
   countryprefix = models.CharField(max_length=200, help_text='')
   cityprefix = models.CharField(max_length=200, help_text='')
   number = models.CharField(max_length=200, help_text='')
   extensionsfrom = models.CharField(max_length=200, help_text='')
   extensionstill = models.CharField(max_length=200, help_text='')
   portscount = models.CharField(max_length=200, help_text='')
   def get_absolute_url(self):
       return reverse('context-detail', args=[str(self.name)])
   def my_get_absolute_url(self):
       return reverse('my-context-detail', args=[str(self.name)])
   def __str__(self):
       return self.name

根据该模型,我创建了一个带有初始部分 init 的ModelForm,其中将抓取用户名。

然后可用的上下文将由用户名过滤。

According to this model I created a ModelForm with an initial section init, in wich the username will be grabbed.
The available contexts will then be filtered by the username.

forms.py

# __init__  stackoverflow.com/questions/291945/how-do-i-filter-foreignkey-choices-in-a-django-modelform/1244586#1244586
# ModelForm learningaboutelectronics.com/Articles/How-to-save-data-from-a-form-to-a-database-table-in-Django.php
# commit    tutorial.djangogirls.org/en/django_forms/#saving-the-form
class MyExtensionCreateForm(forms.ModelForm):
    def __init__(self, context, *args, **kwargs):
        name = kwargs.pop('user')
        super(MyExtensionCreateForm, self).__init__(*args, **kwargs)
        self.fields['context'].queryset = Context.objects.filter(name=name)

    class Meta:
        model = Extension
        fields = '__all__'
#         fields= ["firstname", "lastname", "extension", "password"]

#     def clean_data(self):
#         data = self.cleaned_data
#         # Remember to always return the cleaned data.
#         return data

在视图中,我大胆地想将其保存到数据库中。

表单调用的 user = request.user 部分会将用户名传递给ModelForm,以便我们可以像在forms.py中一样过滤选择。

Than in the view i bassicly want to just save the to the database.
The user=request.user part of the Form Call will pass the username to the ModelForm so we can filter the choices like we did in the forms.py.

views.py

def MyExtensionCreate(request):
    # If this is a POST request then process the Form data
    # if request.method == 'POST':
    # Create a form instance and populate it with data from the request (binding) AND pass the username to the Form
    form = MyExtensionCreateForm(request.POST or None, user=request.user)
    # Check if the form is valid:
    if form.is_valid():
        form = form.save(commit=False)
        # process the data in form.cleaned_data as required
        # form.callerid = "Max"
        # form.username = "telba.de_888"
        # form.context = str(request.user)
        # form.context.queryset = Context.objects.filter(name=request.user)
        form.save()
        # Return to the Extensions List View "My Extensions"
        return HttpResponseRedirect(reverse('my-extensions'))
        # Return to the newly created Extension Detail View
        # return redirect('extension-detail', pk=post.pk)
    # If this is a GET (or any other method) create the default form.
    # else:
    #     # Predefine the Extension.context Attribute with the current Username in GET
    #     form = MyExtensionCreateForm({'context': request.user})
    context = {
        'form': form,
    }

    # def get_form_kwargs(self):
    #     kwargs = super(MyExtensionCreate, self).get_form_kwargs()
    #     kwargs.update({'user': request.user})
    #     return kwargs

    return render(request, 'catalog/extension_form-by-user.html', context)

我创建了一个视频,以显示表单的当前行为。

I created a little Video to show of the Current behavior of the Form.

表单视频

我可以查看表格,选择的方式会像我希望的那样受到限制。
但是提交表单只会重新加载页面,除此之外没有任何作用。
因此它不会将值保存到数据库中,并且我也没有收到任何错误。

I can view the form, and the choices will be limited like I want them to be. But submitting the Form will just reload the Page and does nothing besides it. So it does not save the Values to the Database, and I don't get any Error.

请,有人可以在这里帮助我吗?

Please, can anyone help me out here?

推荐答案

您已将表单的 __ init __ 方法的签名更改为采用 context 作为第一个位置参数。这意味着POST数据不会传递到表单。

You have changed the signature of the form's __init__ method to take context as the first positional argument. This means that the POST data is not being passed to the form.

我不知道您为什么这样做,因为您从未使用上下文。删除该参数。

I don't know why you are doing that, as you never use context. Remove that argument.

这篇关于Django:无法保存表单(ModelForm通过request.user过滤ForeignKey选择)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆