【问题标题】:Required field error happans only when using ajax必填字段错误仅在使用 ajax 时发生
【发布时间】:2021-02-11 20:13:13
【问题描述】:

我有一个名为 SaleEntry 的模型:

class SaleEntry(models.Model):
date = models.DateField()
ebay_price = models.FloatField()
amazon_price = models.FloatField()
ebay_tax = models.FloatField()
paypal_tax = models.FloatField()
tm_fee = models.FloatField(default=0.3)
promoted = models.FloatField(default=0.0)
profit = models.FloatField()
discount = models.FloatField(default=0)
country = models.CharField(max_length=100, default="-----")
user = models.ForeignKey(User, on_delete=models.CASCADE, default=0)

def save(self, *args, **kwargs):
    if not self.pk:  # object is being created, thus no primary key field yet
        change_balance = Balance.objects.get(user=self.user)
        change_balance.balance = change_balance.balance - self.amazon_price - self.tm_fee + self.discount
        change_balance.save()
    
    super(SaleEntry, self).save(*args, **kwargs)

def calc_profit(self):
    return self.ebay_price - self.amazon_price - self.ebay_tax - self.paypal_tax - self.tm_fee - self.promoted + self.discount

def __str__(self):
    return f'{self.user} - {self.profit}'

我有一个表单来处理这个模型 SaleEntryForm:

class SaleEntryForm(ModelForm):
class Meta:
    model = SaleEntry
    fields = "__all__"
    widgets = {
        'date': DateInput(attrs={'class': 'form-control', 'id':'f_date'}),
        'ebay_price': forms.NumberInput(attrs={'class': 'form-control', 'placeholder': 'eBay Price', 'id':'f_ebay_price', 'onkeyup': 'calc_profit()'}),
        'amazon_price': forms.NumberInput(attrs={'class': 'form-control', 'placeholder': 'Amazon Price', 'id':'f_amazon_price', 'onkeyup': 'calc_profit()'}),
        'ebay_tax': forms.NumberInput(attrs={'class': 'form-control col-1', 'placeholder': 'eBay Tax', 'id':'f_ebay_tax', 'onkeyup': 'calc_profit()'}),
        'paypal_tax': forms.NumberInput(attrs={'class': 'form-control col-1', 'placeholder': 'Paypal Tax', 'id':'f_paypal_tax', 'onkeyup': 'calc_profit()'}),
        'tm_fee': forms.NumberInput(attrs={'class': 'form-control col-1', 'placeholder': 'TM Fee', 'id':'f_tm_fee', 'onkeyup': 'calc_profit()'}),
        'promoted': forms.NumberInput(attrs={'class': 'form-control col-1', 'placeholder': 'Promoted', 'id':'f_promoted', 'onkeyup': 'calc_profit()'}),
        'profit': forms.NumberInput(attrs={'class': 'form-control', 'placeholder': 'Profit', 'readonly':'true', 'id':'f_profit'}),
        'discount': forms.NumberInput(attrs={'class': 'form-control', 'placeholder': 'Discount', 'id':'f_discount'}),
        'country': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Country', 'id':'f_country'}),
    }

def __init__(self, *args, **kwargs):
    '''
    relate the sale registration form to the user who created it.
    '''
    user_id = kwargs.pop('user_id')
    super().__init__(*args, **kwargs)
    self.fields['user'] = forms.ModelChoiceField(queryset=User.objects.filter(id=user_id), empty_label=None, initial=User.objects.get(id=user_id))
    self.fields['user'].widget.attrs['class'] = 'no-display'

我在html页面中使用这个表单:

<form id="form_add_sale">
            {% csrf_token %}
            <tr>
                {% for field in form %}
                    {% if field is not form.user %}
                    <td>
                        {{ field }}
                    </td>
                    {% else %}
                        {{ field }}
                    {% endif %}
                {% endfor %}
                <td><input class="btn btn-primary" type="submit" display="inline" name="btn_register_sale"></td>
            </tr>
        </form>

这是将数据发送到服务器的 ajax:

$(document).on("submit", '#form_add_sale', function(e){
    e.preventDefault();
         
    $.ajax({
        url:"{% url 'add_sale' %}",
        type:"POST",
        data:{
            date: $("#f_date").val(),
            ebay_price: $("#f_ebay_price").val(),
            amazon_price: $("#f_amazon_price").val(),
            ebay_tax: $("#f_ebay_tax").val(),
            paypal_tax: $("#f_paypal_tax").val(),
            tm_fee: $("#f_tm_fee").val(),
            promoted: $("#f_promoted").val(),
            profit: $("#f_profit").val(),
            discount: $("#f_discount").val(),
            country: $("#f_country").val(),
        },
        success: function(){
            alert("Created new sale!");
        }
    })
    //.done(function(response){
    //    $("#table_sales").load(location.href + " #table_sales");
    //})
    .fail(function(xhr, status, error){
        var err = eval("(" + xhr.responseText + ")");
            alert(err.Message);
    })
})

提交表单后,我收到下一个错误(在没有 ajax 且视图中代码完全相同的情况下定期提交表单时不会发生该错误):

<ul class="errorlist"><li>user<ul class="errorlist"><li>This field is required.</li></ul></li></ul>

这是 request.POST:

【问题讨论】:

    标签: django ajax django-forms


    【解决方案1】:

    我想你忘记了csrf_token。尝试添加:

    csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
    

    data

    更多信息可以找到here

    【讨论】:

    • 其实我是用decorator做的,只是没解决。无论如何,我解决了我只需要排除用户字段并从视图中添加它的问题。还是谢谢!
    猜你喜欢
    • 2016-07-04
    • 1970-01-01
    • 1970-01-01
    • 2011-10-02
    • 2012-05-11
    • 1970-01-01
    • 1970-01-01
    • 2017-08-31
    • 1970-01-01
    相关资源
    最近更新 更多