简体   繁体   English

Django:保存表单不起作用(ModelForm 通过 request.user 过滤 ForeignKey 选择)

[英]Django: saving the Form does not work (The ModelForm Filters the ForeignKey choices by request.user)

I Managed to Filter the ForeignKey choices "Context.name" by "request.user" with the Code Below.我设法使用下面的代码通过“request.user”过滤了ForeignKey选项“Context.name”。 First, I defined the Models.首先,我定义了模型。

models.py模型.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

According to this model I created a ModelForm with an initial section init , in which the username will be grabbed.根据这个模型,我创建了一个带有初始部分init的 ModelForm,其中将获取用户名。
The available contexts will then be filtered by the username.然后可用的上下文将由用户名过滤。

forms.py表格.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

Than in the view I basically 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.表单调用的user=request.user部分会将用户名传递给 ModelForm,因此我们可以像在 forms.py 中那样过滤选择。

views.py视图.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.我创建了一个小视频来展示表单的当前行为。

Video 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?拜托,有人可以帮我吗?

You have changed the signature of the form's __init__ method to take context as the first positional argument.您已更改表单的__init__方法的签名以将context作为第一个位置参数。 This means that the POST data is not being passed to the form.这意味着 POST 数据没有传递给表单。

I don't know why you are doing that, as you never use context .我不知道你为什么这样做,因为你从不使用context Remove that argument.删除那个论点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM