【问题标题】:django forms views.py - error : inconsistent use of tabs and spaces in indentationdjango forms views.py - 错误:缩进中制表符和空格的使用不一致
【发布时间】:2015-01-11 04:56:10
【问题描述】:

我有一个关于 Gjango 编程的问题。我想从 django 表单中恢复数据以在 views.py 中使用它,但我收到一个错误:缩进中制表符和空格的使用不一致(views.py,第 21 行)。 我尝试使用cleaned_data 或request.POST 我总是发现相同的错误,这是我的源代码: 模型.py

from django.db import models

# Create your models here.

class Personne(models.Model):
    nom=models.CharField(max_length=200)
    prenom=models.CharField(max_length=200)

    def __unicode__(self):
        return self.nom
    def __str__(self):
        return self.nom

forms.py

from django import forms
from application1.models import Personne

class PersonneForm(forms.ModelForm):
        class Meta:
            model=Personne
            #fields = '__all__'
            fields=('nom','prenom')

views.py

from django.shortcuts import render
from django.http import HttpResponseRedirect
from application1.forms import PersonneForm
def get_name(request):
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = PersonneForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            # process the data in form.cleaned_data as required
            # ...
            # redirect to a new URL:

            #I want to recover data here  i tried to use cleaned_data or request.POST and i find the same error
            nom = form.cleaned_data['nom']
            nom=request.POST['nom']

            form.save()


    # if a GET (or any other method) we'll create a blank form
    else:
        form = PersonneForm()

    return render(request, 'name.html', {'form': form})

感谢您的帮助

【问题讨论】:

  • 我使用的是 Django 1.8 版本
  • 你可能想改用nom = form.cleaned_data.get('nom')

标签: python django


【解决方案1】:

在 Python 中混合制表符和空格作为缩进的一种方法是非法的,即 Python 解释器不会接受它,您的应用程序也不会运行,正如您所经历的那样。在 Python 中缩进时,您必须使用空格或制表符。

是否使用制表符或空格,请参考PEP8(Python编码风格指南):

空格是首选的缩进方法。

制表符仅用于与已经缩进制表符的代码保持一致。

重要的是选择一种样式,这样代码就一致了,Guido 选择了空格。

Related question.

【讨论】:

  • 嗨,谢谢你的回答,我用空格换了标签,我也遇到了同样的问题
  • 我评论了cleaned_data['nom'] 并且应用程序成功运行
  • 在您更改了空格选项卡后,您是否仍然收到相同的错误?
  • 是的,同样的问题
  • 好的,如果你遇到同样的错误,你评论的那一行必须加标签
【解决方案2】:

这是您的源文件views.py 的问题,而不是应用程序逻辑或您从一个函数传递到另一个函数的数据的问题。在您的文本编辑器中,搜索选项卡“\t”并将其替换为“”(4 个空格)。

【讨论】:

  • 首先感谢您的帮助,请您说得更清楚些,我是 Django 编程新手。
  • 嗨,埃森。添加了我通常如何处理此问题的图像。大多数情况下,很难区分,因为空格和制表符在编辑器中看起来是一样的。
  • 我想这不是问题,因为我将cleaned_data 与form.save() 放在同一级别,并且我将clean_data 作为注释并且form.save() 通过存储在数据库中成功工作。请原谅
  • 从我们的 cmets 到另一个答案,看起来您正在同时使用制表符和缩进。 “分配前引用的表格”表明实际逻辑存在问题。您可能希望使用错误中的行号创建一个新问题,或者编辑您的问题以包含更改的代码和错误的行号。
猜你喜欢
  • 2020-08-10
  • 2012-10-10
  • 2011-08-06
  • 2015-08-28
  • 2019-10-05
  • 2019-04-15
  • 2020-01-23
  • 2019-07-24
  • 1970-01-01
相关资源
最近更新 更多