首页 > 解决方案 > 从 Ajax Django 请求中的表单获取数据的值

问题描述

提交后,我需要将我的代码重定向到 Django url 中的另一个页面,包括来自我的 view.py 的主键。

我想在我的views.py中取消提交这些代码行

b = Business.objects.get(pk=business.pk)
about = AboutBusiness.objects.create(business=b)

所以我可以获取 about.id 的值并将其添加到我的 ajax 行中,以重定向到此页面;

window.location.href = "/seller/addaboutbusiness/about.id";

模型.py

class Business(models.Model):

    FLIP_TYPE = (
        ('1', 'Buy Out'),
        ('2', 'Partnership')
    )

    TYPE = (
        ('1', 'Business Name'),
        ('2', 'Sole Proprietorship'),
        ('3', 'Partnerships'),
        ('4', 'Limited Partnership'),
        ('5', 'Corporation'),
        ('6', 'Limited Liability Company'),
        ('7', 'Nonprofit Organization'),
        ('8', 'Cooperative')
    )

    user = models.ForeignKey(
        User, related_name='business', on_delete=models.CASCADE)
    flip = models.CharField(
        "Type of Flipping", max_length=150, choices=FLIP_TYPE)

    name = models.CharField('Busniess Name', max_length=50)

    """ status = models.CharField('Registration Status',
                            max_length=50, choices=STATUS) """
    status = models.BooleanField("Regsitration Status", default=True)

    registration = models.CharField(
        'Regsitraion Number', max_length=25, blank=True, null=True)
    t_business = models.CharField(
        "Business Type", max_length=120, choices=TYPE)
    approval = models.BooleanField(default=False)

    created_at = models.DateField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

class AboutBusiness(models.Model):

    """Model definition for AboutBUsiness."""
    business = models.ForeignKey(
        Business, related_name="about", on_delete=models.CASCADE)
    founder = models.CharField(
        "OwnerShip Name", help_text="Seperate the name with comma", max_length=500)
    found = models.IntegerField(
        ("When Found"), choices=YEAR_CHOICES, default=datetime.datetime.now().year)
    about = models.TextField("About The Business")
    #industry = models.CharField(max_length=150)
    industry = models.ManyToManyField(Industry)
    location = models.CharField("Business Location", max_length=120)
    created_at = models.DateField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

视图.py

def AddBusiness(request):

    if request.is_ajax() and request.method == 'POST':
        form = AddBusinessForm(request.POST or None)
        data = {}
        if form.is_valid():

            business = form.save(commit=False)
            user = request.user
            business.user = user
            business.save()
            #b = Business.objects.get(pk=business.pk)
            #about = AboutBusiness.objects.create(business=b)

            data['success'] = True
            return HttpResponse(json.dumps(data), content_type='application/json')
        else:
            data['success'] = False
            return HttpResponse(json.dumps(data), content_type='application/json')
    else:

        form = AddBusinessForm()
        return render(request, 'seller/addbusiness.html', {'form': form})

卖家.js

$(document).on('submit', "#post-form", function (event) {
    event.preventDefault();
    //alert("Ajax Called")
    var businessform = $("#post-form")


    $.ajax({
        url: "addbusiness",
        type: "POST",
        data: businessform.serialize(),
        datatype: "json",
        header: { 'X-CSRFToken': '{% csrf_token %}' },

        success: function (response) {
            console.log($('#post-form').serialize());
            var success = response['success']
            if (success) {
                alert("Form Valid and Created New Business....")
                // window.location = "//www.aspsnippets.com/";
                window.location.href = "/seller/addaboutbusiness/";
                //window.location.replace("{% url 'successpayment' d.slug %}");
                //businessform.reset()
            }
            else {
                alert("The form is having issuess.....")
            }

        },
        failure: function (error) {
            alert("Error occur calling the Django view....")
        }
    })

})

标签: jquerydjangoajax

解决方案


推荐阅读