TabError:缩进中的制表符和空格不一致使用-Integration MailChimp Django

时间:2019-05-17 21:23:05

标签: python ajax django mailchimp

我刚刚使用MailchimpAjax集成到了我的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 ..

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

这是我的代码:

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

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

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

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以获取输入名称:

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:

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代码:

  $('#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);
        }
    }
})

我该如何实现?

1 个答案:

答案 0 :(得分:1)

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

>>> 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,不建议使用)将每个四个空格转换为一个选项卡。

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