基于功能的视图中的Ajax

时间:2019-01-03 10:30:04

标签: django django-forms

我遇到了很多有关如何为ajax设置基于类的视图的教程。示例:

class JoinFormView(FormView):
    form_class = JoinForm
    template_name  = 'forms/ajax.html'
    success_url = '/form-success/'

    def form_valid(self, form):
        response = super(JoinFormView, self).form_valid(form)
        if self.request.is_ajax():
            print(form.cleaned_data)
            data = {
                'message': "Successfully submitted form data."
            }
            return JsonResponse(data)
        else:
            return response

我想知道如何将ajax所需的代码插入此基于函数的视图中。所需的代码是否取决于我是否要异步从数据库中提取或写入数据库?

def my_func_view(request):
    template = 'accounts/profile.html'
    form = Form123(request.POST or None)    

    if request.method == 'POST':
        if form.is_valid():
            instance = form.save(commit=True)
            return redirect('/accounts/profile/')

        else:
            messages.error(request, 'There was an error.')
            context = {'form': form,}
            return render(request, template, context)

    else:
        context = {'form': form,}

    return render(request, template, context)

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

您也对基于函数的视图执行相同的操作。

namespace SchedulingSystem.Controllers
    {
        [Route("api/Sections")]
            public class SectionsController : Controller
            {
               [HttpPost]
               [Route("assign/{sectionId}")]
               public async Task<IActionResult> AssignRoom(int sectionId, [FromBody] SaveRoomSectionAssignmentResource resource)
               {
                  // some code here
               }
            }
        }