ModelChoiceField以10为底的int()的无效文字:'' [英] ModelChoiceField invalid literal for int() with base 10: ''

查看:60
本文介绍了ModelChoiceField以10为底的int()的无效文字:''的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我花了整整一天的时间尝试寻找我想使用FormView实现的自定义功能。当我将FormView与HTML form method = POST一起使用时,大多数情况下我都能得到所需的结果。

So I've spent the day trying to chase down a custom thing that I wanted to achieve using FormView. When I use FormView with HTML form method="POST", I am able to get the desired result, mostly.

如果用户单击提交表单,并且存在空白字段,则他们将收到一条错误消息,告知他们需要该表单。我知道我可以在表单上设置ModelChoiceField,但是正在尝试实现自己的逻辑。

If a user clicks to submit a form and an empty field exists, they get an error message telling them the form is required. I'm aware that I can make the ModelChoiceField required on the form, but was trying to implement my own logic for this.

我通过搜索发现,如果我不通过表单进行任何更新,则使用method = GET更为合适。因此,我切换到该方法,基本上使这种方法起作用了,但是我的错误逻辑仍然无法达到我期望的效果。

I found through my searching that if I'm not updating anything via the form, form method="GET" may be more appropriate. So I switched to that, and basically got this method working, but my error logic still doesn't quite work the way I'd expect.

长话短说,我可以使用表单方法= GET,但是当我尝试在表单上进行验证时,它不起作用。更糟糕的是,如果我尝试包含一个空标签,则会创建无效的文字消息,因为基于此SO ... 如果第一个字段本质上为空,似乎可以指定错误逻辑/验证,这是为了在ModelChoiceField上创建空白的首选。

Long story short, I can use the form method="GET", but when I try to do validation on the form, it doesn't work. Worse yet, if I try to include an empty label, that creates an invalid literal message, because based on this SO...In a Django template, how to specify a dictionary key which is itself an attribute? It doesn't seem possible to specify error logic/validation if the first field is essentially empty, which it is in order to create a blank first choice on ModelChoiceField.

这是我的代码。

表单...

dropdown = forms.ModelChoiceField(queryset=Author.objects.filter(is_active=True),required=False)

def __init__(self, *args, **kwargs):
    # q = kwargs.pop('dropdown', None)
    dropdown = kwargs.pop('dropdown', None)
    super(AuthorByNameForm, self).__init__(*args, **kwargs)
    self.fields['dropdown'].empty_label = ''

HTML ...

<form method="GET" action="{% url 'Main:author_detail' %}">

  <h1 class="class">View By Author</h1>

  <div>
    {{ form.dropdown }}
  </div>

The Views ... FORMVIEW

The Views...FORMVIEW

class AuthorByNameView(LoginRequiredMixin,FormView):
    form_class = AuthorNameForm
    template_name = 'author_by_name.html'

 def get_form_kwargs(self):
     kwargs = super(AuthorByNameView, self).get_form_kwargs()
     kwargs['dropdown'] = self.request.GET.get("dropdown")
     return kwargs

DetailView ....

DetailView....

class AuthorDetailView(LoginRequiredMixin,DetailView):
    model = Author
    template_name = 'author_detail.html'

def get_object(self, queryset=None):
    return get_object_or_404(Author, id=self.request.GET.get("dropdown"))
    return get_object_or_404

模型...

本质上只是用户...具有一对一的UserProfile ...

Essentially just User...with a One to One with UserProfile...

class UserProfile(models.Model):
    user = models.OneToOneField(User,on_delete=models.CASCADE)

基本上,如果我从表单中删除了empty_label行,则该表单会进行验证,前提是queryset不为空。如果我包含了empty_label代码行,并且用户在未选择任何内容的情况下单击了提交按钮,则他们将收到以int()为基数10:’的无效文字。解决此问题的唯一方法似乎是使用empty_label引用使ModelChoiceField required = True。

Essentially, if I removed the empty_label line from my form, the form validates, provided that the queryset isn't empty. If I include the empty_label line of code and the user clicks on the submit button without selecting anything, they get an invalid literal for int() with base 10: '' message. It seems the only way to work around this is to make the ModelChoiceField required=True, with the empty_label reference.

使用请求。我知道,GET的行为似乎与POST不同。当我改用POST时,一切都可以按照我的期望进行,但似乎没有一种方法可以防止用户单击后退按钮时出现的错误消息。

Using the request.GET appears to behave differently than the POST for good reason, I'm aware. When I used the POST instead, everything works exactly as I want it to, except there doesn't appear to be a way to prevent the error message that I'm using to show up if the user clicks on the BACK button.

我今天探索了一些Javascript解决方案,这些解决方案通过此SO
如果用户单击浏览器后退按钮,如何清除Django中的self.add_error?但无济于事。

I explored some Javascript solutions today that were recommeneded via this SO, How To Clear self.add_error in Django if user clicks on browser back button? but to no avail.

还有其他人遇到过这场斗争吗?根据到目前为止的知识,在这种情况下,由于我没有更新有问题的记录并仅显示它们,因此表单method = GET似乎是最有意义的,但是对于关于如何在ModelChoiceField中保持空白的第一位置以及如何在不涉及无效文字消息的情况下对相关字段进行任何类型的验证的我的选择。

Has anyone else encountered this struggle? Based on my knowledge up until this point, in this case since I'm not updating the records in question and just displaying them, form method="GET" would seem to make the most sense, but I seem to be pretty limited as to my options on how I can keep a blank first position in my ModelChoiceField and also do any kind of my own validation on the field in question without encountered the invalid literal message.

预先感谢您的任何想法。

Thanks in advance for any thoughts.

推荐答案

利用此SO .... 如何防止在HTML表单输入字段值为空的情况下提交 我能够确定最好的解决方法是在我的代码中添加以下Javascript ...

Leveraging this SO....How to prevent submitting the HTML form's input field value if it empty I was able to determine that the best way to go about this was to add the following Javascript to by my code...

$('form').submit(function() {
  var dropdown = $('#id_dropdown').val();
  if (dropdown === undefined || dropdown === "") {
    $('#id_dropdown').attr('name', '' );
  } else {
    $('#id_dropdown').attr('name', 'dropdown');
  }
});
  });

上面的代码强制使用404而不是我之前收到的无效文字消息。

The code above forces a 404 instead of the invalid literal message that I was getting before.

这篇关于ModelChoiceField以10为底的int()的无效文字:''的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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