Django Python POST方法未写入数据库 [英] Django Python POST Method not writing to database

查看:23
本文介绍了Django Python POST方法未写入数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我的POST方法有问题,未写入数据库且未显示在管理站点中.

I now have an issue with my POST Method not writing to the database and not showing in Admin site.

views.py文件将一直工作到到达'if form.is_valid()'为止,但除此之外没有更多.我究竟做错了什么?请帮忙,我花了很多时间来寻找答案,但无济于事.

the views.py file works until it gets to the 'if form.is_valid()' but doesn't go any further than that. What am I doing wrong? Please help, I've spent time trying to search for the answer but to no avail.

代码如下

urls.py

path('weekly/', user_views.weekly, name='weekly'),

views.py

def weekly(request):
    if request.method == 'POST':
        form = SubscriptionForm(request.POST)
        print('I got this far 3!')
        if form.is_valid():
            form.save()
            messages.success(request, 'Thank you for your payment!')
            return redirect('classes')
        else:
            return render(request, 'clubex/weekly.html', {'title': '1 Week Free'})
    else:
        return render(request, 'clubex/weekly.html',  {'title': '1 Week Free'})

models.py(这些名称是否必须与HTML文档中的"id"相匹配?)

models.py (do these names have to match the 'id' in the HTML doc?)

class Subscription(models.Model):
    firstName = models.CharField(max_length=100)
    lastName = models.CharField(max_length=100)
    username = models.CharField(max_length=100)
    sub_type = models.CharField(max_length=50)
    email = models.EmailField(max_length=100)
    address = models.CharField(max_length=100)
    address2 = models.CharField(max_length=100)
    state = models.CharField(max_length=100)
    country = models.CharField(max_length=100)
    zip = models.CharField(max_length=10)
    same_address = models.BooleanField()
    save_info = models.BooleanField()
    credit = models.BooleanField()
    debit = models.BooleanField()
    paypal = models.BooleanField()
    cc_name = models.CharField(max_length=100)
    cc_number = models.CharField(max_length=20)
    cc_expiration = models.CharField(max_length=10)
    cc_cvv = models.IntegerField()

    def __str__(self):
        return f'{self.firstName} {self.lastName} {self.sub_type}'

forms.py(这些名称必须与HTML文档中的"id"相匹配吗?)

forms.py (do these names have to match the 'id' in the HTML doc?)

class SubscriptionForm(forms.ModelForm):
    class Meta:
        model = Subscription
        fields = [
            'firstName',
            'lastName',
            'username',
            'sub_type',
            'email',
            'address',
            'address2',
            'state',
            'country',
            'zip',
            'same_address',
            'save_info',
            'credit',
            'debit',
            'paypal',
            'cc_name',
            'cc_number',
            'cc_expiration',
            'cc_cvv',
        ]

weekly.html(请注意指向验证js文件的链接)

weekly.html (note the link to the validating js file)

<link rel="canonical" href="https://getbootstrap.com/docs/4.5/examples/checkout/">

    <!-- Bootstrap core CSS -->
<link href="../assets/dist/css/bootstrap.min.css" rel="stylesheet">
<Link rel="stylesheet" href="{% static 'ClubEx/form-validation.css' %}" type="text/css" >
 <h2>Checkout form for {{ user.username }}</h2>
    <p class="lead">Hi {{ user.username }}. Please check and fill out the following form to complete your subscription application. </p>
  </div>

  <div class="row">
    <div class="col-md-4 order-md-2 mb-4">
      <h4 class="d-flex justify-content-between align-items-center mb-3">
        <span class="text-muted">Your cart</span>
        <span class="badge badge-secondary badge-pill">1</span>
      </h4>
      <ul class="list-group mb-3">
        <li class="list-group-item d-flex justify-content-between lh-condensed">
          <div>
            <h6 class="my-0">Product name</h6>
            <small class="text-muted">1 Free Weekly Subscription</small>
          </div>
          <span class="text-muted">Free</span>
        </li>
        <li class="list-group-item d-flex justify-content-between">
          <span>Total (NZD)</span>
          <strong>0.00</strong>
        </li>
      </ul>
    </div>
    <div class="col-md-8 order-md-1">
      <form method="post" action="/weekly/" class="needs-validation">
        {% csrf_token %}
      <h4 class="mb-3">Billing address</h4>
        <div class="row">
          <div class="col-md-6 mb-3">
            <label for="firstName">First name</label>
            <input type="text" class="form-control" id="firstName" placeholder="" required>
            <div class="invalid-feedback">
              Valid first name is required.
            </div>
          </div>
          <div class="col-md-6 mb-3">
            <label for="lastName">Last name</label>
            <input type="text" class="form-control" id="lastName" placeholder="" value="" required>
            <div class="invalid-feedback">
              Valid last name is required.
            </div>
          </div>
        </div>

        <div class="mb-3">
          <label for="username">Username</label>
          <div class="input-group">
            <div class="input-group-prepend">
              <span class="input-group-text">@</span>
            </div>
            <input type="text" class="form-control" id="username" placeholder="Username" required>
            <div class="invalid-feedback" style="width: 100%;">
              Your username is required.
            </div>
          </div>
        </div>
       <div class="mb-3">
          <label for="sub_type">Subscription Type</label>
          <select class="custom-select d-block w-100" id="sub_type" required>
            <option value="">Choose...</option>
            <option>Weekly $ Free</option>
            <option>Monthly $10</option>
            <option>Annual $100</option>
          </select>
          <div class="invalid-feedback">
            Please select a valid Subscription.
          </div>
        </div>
        <div class="mb-3">
          <label for="email">Email <span class="text-muted">(Optional)</span></label>
          <input type="email" class="form-control" id="email" placeholder="you@example.com">
          <div class="invalid-feedback">
            Please enter a valid email address for shipping updates.
          </div>
        </div>

        <div class="mb-3">
          <label for="address">Address</label>
          <input type="text" class="form-control" id="address" placeholder="1234 Main St" required>
          <div class="invalid-feedback">
            Please enter your shipping address.
          </div>
        </div>

        <div class="mb-3">
          <label for="address2">Address 2 <span class="text-muted">(Optional)</span></label>
          <input type="text" class="form-control" id="address2" placeholder="Apartment or suite">
        </div>

        <div class="row">
          <div class="col-md-4 mb-3">
            <label for="state">State</label>
            <select class="custom-select d-block w-100" id="state" required>
              <option value="">Choose...</option>
              <option>Auckland</option>
              <option>Christchurch</option>
            </select>
            <div class="invalid-feedback">
              Please select a valid country.
            </div>
          </div>
          <div class="col-md-5 mb-3">
            <label for="country">Country</label>
            <select class="custom-select d-block w-100" id="country" required>
              <option value="">Choose...</option>
              <option>New Zealand</option>
             </select>
            <div class="invalid-feedback">
              Please provide a valid City.
            </div>
          </div>
          <div class="col-md-3 mb-3">
            <label for="zip">Postcode</label>
            <input type="text" class="form-control" id="zip" placeholder="" required>
            <div class="invalid-feedback">
              Postcode required.
            </div>
          </div>
        </div>
        <hr class="mb-4">
        <div class="custom-control custom-checkbox">
          <input type="checkbox" class="custom-control-input" id="same_address">
          <label class="custom-control-label" for="same_address">Shipping address is the same as my billing address</label>
        </div>
        <div class="custom-control custom-checkbox">
          <input type="checkbox" class="custom-control-input" id="save_info">
          <label class="custom-control-label" for="save_info">Save this information for next time</label>
        </div>
        <hr class="mb-4">

        <h4 class="mb-3">Payment</h4>

        <div class="d-block my-3">
          <div class="custom-control custom-radio">
            <input id="credit" name="paymentMethod" type="radio" class="custom-control-input" checked required>
            <label class="custom-control-label" for="credit">Credit card</label>
          </div>
          <div class="custom-control custom-radio">
            <input id="debit" name="paymentMethod" type="radio" class="custom-control-input" required>
            <label class="custom-control-label" for="debit">Debit card</label>
          </div>
          <div class="custom-control custom-radio">
            <input id="paypal" name="paymentMethod" type="radio" class="custom-control-input" required>
            <label class="custom-control-label" for="paypal">PayPal</label>
          </div>
        </div>
        <div class="row">
          <div class="col-md-6 mb-3">
            <label for="cc_name">Name on card</label>
            <input type="text" class="form-control" id="cc_name" placeholder="" required>
            <small class="text-muted">Full name as displayed on card</small>
            <div class="invalid-feedback">
              Name on card is required
            </div>
          </div>
          <div class="col-md-6 mb-3">
            <label for="cc_number">Credit card number</label>
            <input type="text" class="form-control" id="cc_number" placeholder="" required>
            <div class="invalid-feedback">
              Credit card number is required
            </div>
          </div>
        </div>
        <div class="row">
          <div class="col-md-3 mb-3">
            <label for="cc_expiration">Expiration</label>
            <input type="text" class="form-control" id="cc_expiration" placeholder="" required>
            <div class="invalid-feedback">
              Expiration date required
            </div>
          </div>
          <div class="col-md-3 mb-3">
            <label for="cc_cvv">CVV</label>
            <input type="text" class="form-control" id="cc_cvv" placeholder="" required>
            <div class="invalid-feedback">
              Security code required
            </div>
          </div>
        </div>
        <hr class="mb-4">
          <button class="btn btn-primary btn-lg btn-block" type="submit">Pay Now!</button>
      </form>
    </div>
  </div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
        integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
        crossorigin="anonymous"></script>
      <script>window.jQuery || document.write('<script src="../assets/js/vendor/jquery.slim.min.js"><\/script>')</script>
      <script src="../assets/dist/js/bootstrap.bundle.min.js"></script>
        <script src="form-validation.js"></script>

      {% endblock content %}

从终端

I got this far 3!
[14/Sep/2020 10:49:41] "POST /weekly/ HTTP/1.1" 200 11778
Not Found: /weekly/form-validation.js
Not Found: /assets/dist/css/bootstrap.min.css
Not Found: /assets/dist/js/bootstrap.bundle.min.js
[14/Sep/2020 10:49:41] "GET /weekly/form-validation.js HTTP/1.1" 404 5242
[14/Sep/2020 10:49:41] "GET /assets/dist/css/bootstrap.min.css HTTP/1.1" 404 5266
[14/Sep/2020 10:49:41] "GET /assets/dist/js/bootstrap.bundle.min.js HTTP/1.1" 404 5281
Not Found: /assets/dist/js/bootstrap.bundle.min.js
[14/Sep/2020 10:49:41] "GET /assets/dist/js/bootstrap.bundle.min.js HTTP/1.1" 404 5281
Not Found: /weekly/form-validation.js
[14/Sep/2020 10:49:41] "GET /weekly/form-validation.js HTTP/1.1" 404 5242

推荐答案

该表单无效.使用sub_type和state,您传递的是 choicefield ,而模型需要的是 charfield

The form is not valid. With sub_type and state, you are passing a choicefield and the model needs a charfield

您的表单必须为:

class SubscriptionForm(forms.ModelForm):
    firstName = forms.CharField(
        required=True,
        label="First Name",
        widget=forms.TextInput( attrs = {
                'type':"text",
                'placeholder':"First name",
                'class':'form-control', # html input class
        })    
    )

    sub_type = forms.ChoiceField(
        required=True,
        label="Subscription Type",
        choices= (
            ('Option 1', 'Choose'),
            ('Option 2', 'Weekly $ Free'),
            ...
        ),
        widget=forms.Select( attrs = {
            'class':'your-css-class'
        })
    )

    ...

将表单传递到您的html

pass the form to your html

def weekly_get(request):
    form = SubscriptionForm()
    return render('weekly.html',{'form':form })

然后,您的html

<form method="post" action="/weekly/" class="needs-validation">
{% csrf_token %}
    
{% for field in form %}
    <div class="row">
        <div class="col-md-6 mb-3">
            {{field.label_tag}}
            {{field}}
        </div>
    </div>
{% endfor %}

</form>

这篇关于Django Python POST方法未写入数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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