通过具有2个视图和ajax的模型表单更新模型时处理重定向

时间:2016-03-24 16:12:05

标签: python django django-models django-forms

我正在使用ajax和两个视图。一切正常,但我无法弄清楚如何最好地处理重定向。显然,将表单在一个页面上呈现两次然后再呈现另一个页面是多余的。如何在不重定向用户的情况下更新模型?

forms.py

class RecruitForm(forms.ModelForm):
    jobnum = forms.ModelChoiceField(queryset=Job.objects.all())
    class Meta:
        model = Job
        fields = ['jobnum','rec_count']

view.py

def recruiting(request):
  if request.method == 'POST':
    recruit_form = RecruitForm(request.POST or None)
    if recruit_form.is_valid():
      t = Job.objects.get(jobnum=recruit_form.cleaned_data.get('jobnum'))
      t.jobnum = recruit_form.cleaned_data.get('jobnum')
      t.rec_count = recruit_form.cleaned_data.get('rec_count')
      t.save()

def edit(request): #testing

  jobnum = request.GET.get('jobnum')
  job_list = Job.objects.filter(jobnum=jobnum)
  json_data = serializers.serialize('json', job_list)
  a = json.loads(json_data)
  a = a[0]['pk']
  j = Job.objects.get(pk=a) 
  form = RecruitForm(request.POST or None ,instance=j)
  instance = form.save(commit=False)
  instance.save()



  return render(request, "editrec.html", {"form":form})

javascript.js

$('.row2').click(function(){
    var a = $(this).data('jobnum')
    $.ajax({
    url: "/edit/",
    data: {'jobnum':a},
    success: function(data) {

        console.log(data)
        $(".divtest").html(data);

        document.getElementById('editform').action='../edit/?jobnum=' + encodeURIComponent(a);    
    },
    });
});

urls.py

url(r'^edit/$','SiteTwo.views.edit', name='edit'), #testing

editrec.html

{% load staticfiles %}
{% load crispy_forms_tags %}

{% block content %}

    <form method='POST' id='editform' action = '' class='givemewhite'>{% csrf_token %}
    {{form|crispy}}
    <button class = 'btn btn-default' name='edit'/>Submit</button>
    </form> 

{% endblock %}

forms.py

class RecruitForm(forms.ModelForm):
    jobnum = forms.ModelChoiceField(queryset=Job.objects.all())
    class Meta:
        model = Job
        fields = ['rec_count']

2 个答案:

答案 0 :(得分:1)

我认为您不喜欢用户在提交通过AJAX加载的表单时导航到新页面的事实。为防止这种情况发生,您必须在加载的表单中捕获'submit'事件。您可以将javascript.js更改为:

$('.row2').click(function(){
    var a = $(this).data('jobnum')
    $.ajax({
    url: "/edit/",
    data: {'jobnum':a},
    success: function(data) {

        console.log(data)
        var form = jQuery(".divtest").html(data).find('#editform');
        form.attr('action', '../edit/?jobnum=' + encodeURIComponent(a));
        form.submit(function () {
            jQuery.ajax(form.attr('action'), {
                data: form.serialize(),
                method: form.attr('method').toUpperCase(),
                success: function () {
                    /* Reload the containing document to show new data. */
                    document.location.reload();
                }
            });
            /* Disable propagation and prevent default action (browser navigates to new page and submits). */
            return false;
        });
    },
    });
});

答案 1 :(得分:0)

def recruiting(request):
   # Create custom form to use here, taking only one input that is job that you want to change. you can use modelchoicefield for list.


def edit(request): #testing

     jobnum = request.GET.get('jobnum')
     job_list = Job.objects.filter(jobnum=jobnum)
     json_data = serializers.serialize('json', job_list)
     a = json.loads(json_data)
     a = a[0]['pk']
     j = Job.objects.get(pk=a) 
     form = RecruitForm(request.POST or None ,instance=j)
     if request.POST:
         if form.is_valid():
              form.save()

     return render(request, "editrec.html", {"form":form})