TabError:缩进中的制表符和空格不一致使用-Integration MailChimp Django [英] TabError: inconsistent use of tabs and spaces in indentation - Integration MailChimp Django

查看:127
本文介绍了TabError:缩进中的制表符和空格不一致使用-Integration MailChimp Django的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚使用AjaxMailchimp集成到了我的Django项目中.电子邮件地址字段正常工作,我可以在Mailchimp列表和数据库中获取电子邮件.现在,当我尝试添加一个允许用户将其名字添加到表单中的字段时,我不断收到诸如以下错误:from .utils import SendSubscribeMail File "C:\Users\locq\Desktop\Coding\SEARCH_APP\venv\src\search\utils.py", line 8 self.fname = fname ^ TabError: inconsistent use of tabs and spaces in indentation ..

I have just integrated Mailchimp to my Django Project using Ajax. The email address field is working properly and I'm able to get the email in both my Mailchimp list and my database. Now when I try to add a field that let a user add his first name to the form, I keep getting errors like this one for example: from .utils import SendSubscribeMail File "C:\Users\locq\Desktop\Coding\SEARCH_APP\venv\src\search\utils.py", line 8 self.fname = fname ^ TabError: inconsistent use of tabs and spaces in indentation..

那么我该如何添加FNAME字段,并在提交时将数据发送到mailchimp?

So how can I add a FNAME field and send the datas to mailchimp on submit?

这是我的代码:

在我的Settings.p中,我在底部添加了Mailchimp凭据,如下所示:

In my Settings.p I added my Mailchimp credentials at the bottom like this:

MAILCHIMP_API_KEY = '767ba************-us6'
MAILCHIMP_SUBSCRIBE_LIST_ID = '45c*******'

我创建了一个utils.py文件来使用Threading,Mailchimp程序包,并从设置中导入我的凭据:

I created a utils.py file to use Threading, the Mailchimp package and import my credentials from the settings:

import threading
import mailchimp
from django.conf import settings

class SendSubscribeMail(object):
    def __init__(self, email, fname):
        self.email = email
        self.fname = fname
        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True
        thread.start()

    def run(self):
        API_KEY = settings.MAILCHIMP_API_KEY
        LIST_ID = settings.MAILCHIMP_SUBSCRIBE_LIST_ID
        api = mailchimp.Mailchimp(API_KEY)
        try:
            api.lists.subscribe(LIST_ID, {'email': self.email}, merge_vars={'FNAME': self.fname}, double_optin=False)
        except:
            return False

自定义Def以获取输入名称:

Custom Def to get the input names:

def subscribe(request):
    if request.method == 'POST':
        fname = request.POST['fname_id']
        Subscribe.objects.create(fname_id = fname)
        email = request.POST['email_id']
        email_qs = Subscribe.objects.filter(email_id = email)
        if email_qs.exists():
            data = {"status" : "404"}
            return JsonResponse(data)
        else:
            Subscribe.objects.create(email_id = email)
            SendSubscribeMail(email, fname) # Send the Mail, Class available in utils.py
    return HttpResponse("/")

我用来在数据库的Subscribe表中添加电子邮件(和fname)的models.py:

The models.py I use to add the email (and fname) in the Subscribe table of my database:

class Subscribe(models.Model):
    email_id = models.EmailField()
    fname_id = models.CharField(max_length=255, blank=True, null=True, default='')
    timestamp = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.email_id

我的html表单:

<div class="signup subs-form">

  <div class="header">
    <p>Sign Up For Beta</p>
  </div>
  <div class="description">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna.</p>
  </div>

  <form method="POST" id="subscribe" class="subs-form">
    {% csrf_token %}
    <div>
      <input type="email" class="button-" id="email" name="email_id" placeholder="E-mail">
      <div class="input">
        <input type="text" class="button-" id="fname" name="fname_id" placeholder="First Name">
        <input type="submit" class="button-" id="submit" value="Join">
      </div>
    </div>
  </form>

</div>

最后,这是我在页面底部的Ajax代码:

And finally, here's the Ajax code I have at the bottom of my page:

  $('#subscribe').submit(function(e){
      e.preventDefault();
      var email_id = $("#email").val();
      if(email_id){
        var csrfmiddlewaretoken = csrftoken;
        var fname_id = $("#fname").val();
        var email_data = {"email_id": email_id,
                          "fname_id": fname_id,
                          "csrfmiddlewaretoken" : csrfmiddlewaretoken};
        $.ajax({
          type : 'POST',
          url :  '/subscribe/',
          data : email_data,
          success : function(response){
            $('#email').val('');
            if(response.status == "404"){
              alert("This Email is already been subscribed!");
            }
            else{
              alert("Thank you for Subscribing! Please Check your Email to Confirm the Subscription");
            }
          },
          error: function(response) {
            alert("Sorry Something went Wrong");
            $('#email').val('');
          }
        });
        return false;
      }
      else{
        alert("Please provide correct email!");
      }
  });


function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
var csrftoken = jQuery("[name=csrfmiddlewaretoken]").val();

function csrfSafeMethod(method) {
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
})

我该如何实现?

推荐答案

根据python文档,python不能混合制表符和空格进行缩进,根据PEP-8,每个缩进级别应使用四个空格.当我尝试这样做时是真的:

According to the python documentation, python cannot mix tabs and spaces for indentation, and according to PEP-8, four spaces should be used for each indent level. When I attempt this it is true:

>>> for i in range(20):
    'indent with tabs'
    'indent with spaces'

SyntaxError: inconsistent use of tabs and spaces in indentation

如果您拥有python IDE,而不仅仅是用记事本或TextEdit之类的方式编写它们,则它应该将每个选项卡转换为四个空格,或者(由于PEP-8,不建议使用)将每个四个空格转换为一个选项卡.

If you have a python IDE, not just writing them in, say Notepad or TextEdit, it should convert each tab to four spaces, or (not recommended because of PEP-8) every 4 four spaces to one tab.

您可以使用Ctrl+H组合查找/替换每个带有4个空格的标签(这不会影响您的实际代码;字符串中的标签应为'\t')

you can use the Ctrl+H combination to find/replace each tab with 4 spaces (this will not affect your actual code; your tabs in strings should be '\t')

这篇关于TabError:缩进中的制表符和空格不一致使用-Integration MailChimp Django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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