为什么我的表格总是无效?

时间:2018-01-29 00:38:48

标签: python ajax django forms

我可以使用html按钮提交我的表单但它可以工作,但我想要一个字段的控件,我使用javascript函数来做到这一点,所以我改变了我的按钮,我用ajax调用我的视图。 如果我的表单无效(这意味着如果有一些字段为空)我希望那些以红色(或类似的东西)为边界的字段以及可能的错误消息(此字段是必需的),就像之前发生的那样,使用html按钮来打电话给视图。

我的 future: <Task finished coro=<handle_echo() done, defined at "E:\Projects\AsyncIOserver.py:3> exception=UnicodeDecodeError('utf-8', b'\xff\x00\x00\x00\x00\x00\x00\x00\x01\x7f', 0, 1, 'invalid start byte')> Traceback (most recent call last): File "E:\Projects\AsyncIOserver.py", line 6, in handle_echo message = data.decode() UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

form.py

我的class PostForm(forms.ModelForm): title_it = forms.CharField(label='Titolo (it)', widget=forms.TextInput()) title_en = forms.CharField(label='Title (en)', widget=forms.TextInput()) text_it = forms.CharField(label='Testo (it)', widget=forms.Textarea(attrs={'rows':"20", 'cols':"100"})) text_en = forms.CharField(label='Text (en)', widget=forms.Textarea(attrs={'rows':"20", 'cols':"100"})) views = forms.IntegerField(widget=forms.HiddenInput(), initial=1) class Meta: model = Post fields = ('title_it', 'title_en', 'text_it', 'text_en', 'tags', 'views')

models.py

class Post(models.Model): title = MultilingualCharField(_('titolo'), max_length=64) text = MultilingualTextField(_('testo')) ... MultilingualCharField差不多(可能不是问题所在):

MultilingualCharField

我的class MultilingualCharField(models.CharField): def __init__(self, verbose_name=None, **kwargs): self._blank = kwargs.get("blank", False) self._editable = kwargs.get("editable", True) #super(MultilingualCharField, self).__init__(verbose_name, **kwargs) super().__init__(verbose_name, **kwargs) def contribute_to_class(self, cls, name, virtual_only=False): # generate language specific fields dynamically if not cls._meta.abstract: for lang_code, lang_name in settings.LANGUAGES: if lang_code == settings.LANGUAGE_CODE: _blank = self._blank else: _blank = True rel_to = None if hasattr(self, 'rel'): rel_to = self.rel.to if self.rel else None elif hasattr(self, 'remote_field'): rel_to = self.remote_field.model if self.remote_field else None localized_field = models.CharField(string_concat( self.verbose_name, " (%s)" % lang_code), name=self.name, primary_key=self.primary_key, max_length=self.max_length, unique=self.unique, blank=_blank, null=False, # we ignore the null argument! db_index=self.db_index, #rel=self.rel,#AttributeError con django 2.0 rel=rel_to, default=self.default or "", editable=self._editable, serialize=self.serialize, choices=self.choices, help_text=self.help_text, db_column=None, db_tablespace=self.db_tablespace ) localized_field.contribute_to_class(cls, "%s_%s" % (name, lang_code),) def translated_value(self): language = get_language() val = self.__dict__["%s_%s" % (name, language)] if not val: val = self.__dict__["%s_%s" % (name, settings.LANGUAGE_CODE)] return val setattr(cls, name, property(translated_value)) def name(self): name_translated='name'+settings.LANGUAGE_CODE return name_translated class MultilingualTextField(models.TextField): def __init__(self, verbose_name=None, **kwargs): self._blank = kwargs.get("blank", False) self._editable = kwargs.get("editable", True) super().__init__(verbose_name, **kwargs) def contribute_to_class(self, cls, name, virtual_only=False): # generate language specific fields dynamically if not cls._meta.abstract: for lang_code, lang_name in settings.LANGUAGES: if lang_code == settings.LANGUAGE_CODE: _blank = self._blank else: _blank = True rel_to = None if hasattr(self, 'rel'): rel_to = self.rel.to if self.rel else None elif hasattr(self, 'remote_field'): rel_to = self.remote_field.model if self.remote_field else None localized_field = models.TextField(string_concat( self.verbose_name, " (%s)" % lang_code), name=self.name, primary_key=self.primary_key, max_length=self.max_length, unique=self.unique, blank=_blank, null=False, # we ignore the null argument! db_index=self.db_index, #rel=self.rel, rel=rel_to, default=self.default or "", editable=self._editable, serialize=self.serialize, choices=self.choices, help_text=self.help_text, db_column=None, db_tablespace=self.db_tablespace ) localized_field.contribute_to_class(cls, "%s_%s" % (name, lang_code),) def translated_value(self): language = get_language() val = self.__dict__["%s_%s" % (name, language)] if not val: val = self.__dict__["%s_%s" % (name, settings.LANGUAGE_CODE)] return val setattr(cls, name, property(translated_value))

views.py

我的@staff_member_required def post_new(request): context_dict=services.get_base_data_for_views(request) if request.method == "POST" and request.is_ajax(): form = PostForm(request.POST) print('form', form) if form.is_valid(): ... else: print('form.errors', form.errors) return render(request, 'blog/post_edit.html', context_dict) else: form = PostForm() context_dict['form']=form return render(request, 'blog/post_edit.html', context_dict)

template.html

我的<button class="btn btn-success" onclick="save_post(event, 'publish')">{% trans "Pubblica" %}</button>

javascript.js

function save_post(event, action) { event.preventDefault(); $.ajax({type: 'POST', url: url_post, data: { //'csrfmiddlewaretoken': '{{csrf_token}}', action: action, }, success: function (lista) { console.log('success') } }); print(form)(Campo nascosto =字段隐藏; Questocampoèobbligatorio=此字段为必填项):

views.py

我在form <tr><td colspan="2"><ul class="errorlist nonfield"><li>(Campo nascosto view s) Questo campo è obbligatorio.</li></ul></td></tr> <tr><th><label for="id_title_it">Titolo (it):</label></th><td><ul class="errorli st"><li>Questo campo è obbligatorio.</li></ul><input type="text" name="title_it" required id="id_title_it" /></td></tr> <tr><th><label for="id_title_en">Title (en):</label></th><td><ul class="errorlis t"><li>Questo campo è obbligatorio.</li></ul><input type="text" name="title_en" required id="id_title_en" /></td></tr> <tr><th><label for="id_text_it">Testo (it):</label></th><td><ul class="errorlist "><li>Questo campo è obbligatorio.</li></ul><textarea name="text_it" rows="20" r equired id="id_text_it" cols="100"> </textarea></td></tr> <tr><th><label for="id_text_en">Text (en):</label></th><td><ul class="errorlist" ><li>Questo campo è obbligatorio.</li></ul><textarea name="text_en" rows="20" re quired id="id_text_en" cols="100"> </textarea></td></tr> <tr><th><label for="id_tags">Tag:</label></th><td><ul class="errorlist"><li>Ques to campo è obbligatorio.</li></ul><input type="text" name="tags" required autoco mplete="off" id="id_tags" /><br /><span class="helptext">Una lista di tag separa ti da virgola.</span><input type="hidden" name="views" id="id_views" /></td></tr > 中的print(form.errors)(Una lista di tag separa ti da virgola =用逗号分隔的标签列表:

views.py

如果我写了一个新表单并且我将字段留空,则不会引发错误,但<ul class="errorlist"><li>text_it<ul class="errorlist"><li>Questo campo è obblig atorio.</li></ul></li><li>text_en<ul class="errorlist"><li>Questo campo è obblig atorio.</li></ul></li><li>views<ul class="errorlist"><li>Questo campo è obbligat orio.</li></ul></li><li>tags<ul class="errorlist"><li>Questo campo è obbligatori o.</li></ul></li><li>title_it<ul class="errorlist"><li>Questo campo è obbligator io.</li></ul></li><li>title_en<ul class="errorlist"><li>Questo campo è obbligato rio.</li></ul></li></ul> 会给出form.is_valid。如果我写一个字段然后将其删除,然后提交该字段以红色为边框,False给出form.is_valid。如果我写完所有字段,False仍然会form.is_valid。所以我的表格永远不会有效

编辑:以下这些行无效

如果我离开Falsetext_ittext_entagsform.is_valid(),我会看到该字段带有红色边框(但没有错误消息{ {1}})。如果我将Falsethis field is requiredtitle_it再次title_en,但我看不到任何红色边框。为什么呢?

0 个答案:

没有答案