Pk从django url中丢失

dohp0rv5  于 2023-06-25  发布在  Go
关注(0)|答案(2)|浏览(117)

我有两个观点,定义如下:

class IpsychCaseView(LoginRequiredMixin, TemplateView):
    model = IpsychCase
    template_name = "ipsych/ipsych_scz.html"
    
    def get(self, *args, **kwargs):
        p = 'antipsychotic'
        return self.render_to_response(
            { "page_title": p.capitalize()
             ```})
   def post(self, *args, **kwargs):
        p='antipsychotic'
        ipsychcaseform = IpsychCaseForm(data=self.request.POST)

        ipsychcaseform = IpsychCaseForm
    if ipsychcaseform.is_valid():
            print('case valid')
            ipsychcase_instance = ipsychcaseform.save()
            ipsychcase_instance.user = self.request.user
            ipsychcase_instance.save()
            
            if ipsychvisitform.is_valid():
                ipsychvisit_instance = ipsychvisitform.save(commit=False)
                ipsychvisit_instance.ipsychcase = ipsychcase_instance
                ipsychvisit_instance.save()
        u = reverse("ipsych_results", kwargs = {"ipsychcase_id": ipsychvisit_instance.ipsychvisit_id})
        print(f'the url being passed to redirect is {u}')
        return redirect(u)

class ResultsView(TemplateView):
    template_name = "ipsych/ipsych_results.html"

    def get(self, request, *args, **kwargs):
        ipsychcase_id = kwargs["ipsychcase_id"]
        results = ip.scz_alg(ipsychcase_id)

        context = {
            "ipsychcase_id": ipsychcase_id,
            "results_intro": results["results_intro"],
            # Add other result values to the context as needed
        }
        return self.render_to_response(context)

    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(*args, **kwargs)
        print(f'the id passed to results view is {context["ipsychcase_id"]}')
        context["ipsychcase_id"] = self.kwargs["ipsychcase_id"]
        results = ip.scz_alg(context["ipsychcase_id"])
        # context['se_heatmap_image'] = results['se_heatmap_image']
        # context['meds_info'] = results['meds_info']
        # context['mse'] = results['mse']
        # context['score_image'] = results['score_image']
        # context['results_intro'] = results['results_intro']
        for key, value in results.items():
            context[key] = value
        print(context["ipsychcase_id"])
        print(context.keys())
        return context
    
    def post(self, *args, **kwargs):
        # if 'download_report' in self.request.POST:
        context = super().get_context_data()
        print(f'This is the id in the results post {context["ipsychcase_id"]}')
        context["ipsychcase_id"] = self.kwargs["ipsychcase_id"]
        results = ip.scz_alg(context["ipsychcase_id"], imagetype = 'png')
        response = download_report(results, self.request.user)
        return response

urls.py是:

path(
        "ipsych/",
        view=ipsych_views.IpsychCaseView.as_view(),
        name="ipsych",
    ),

    path(
        route='ipsych/processed/<ipsychcase_id>/',
        view=ipsych_views.ResultsView.as_view(),
        name='ipsych_results'),

模板包含一些 AJAX 来支持选项卡式表单:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script type="text/javascript" src="{% static 'js/jquery.formset.js' %}"></script>

<script>
    $(document).ready(function() {
        // Submit all forms when the submit button is clicked
        $('#tabbed-form').submit(function(event) {
            event.preventDefault();
            console.log('Form submitted'); 
            
            // Collect the data from all the forms
            var formData = new FormData();
            formData.append('csrfmiddlewaretoken', $('input[name="csrfmiddlewaretoken"]').val());
            console.log('1 step'); 
            $('#tabbed-form .tab-pane').each(function(index) {
                var formFields = $(this).find('input, select, textarea').serialize();
                var fieldsArray = formFields.split('&');

                fieldsArray.forEach(function(field) {
                    var keyValue = field.split('=');
                    formData.append(keyValue[0], decodeURIComponent(keyValue[1]));
                });
       

                console.log(formData); 
            });
            
            // Send the data using AJAX
            $.ajax({
                url: '{% url "ipsych" %}',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function(response) {
                    window.location.href = '/ipsych/processed/{{ipsychcase_id}}/';
                },
                error: function(xhr, status, error) {
                    // Handle the error
                }
            });
        });
    });
</script>

正在传递到重定向的URL是/ipsych/processed/8b 429 f6 d-8538- 4af 6 - 90 b 9 - 102168887 e34/
当我在浏览器中输入http://localhost:8000/ipsych/processed/8b429f6d-8538-4af6-90b9-102168887e34/时,后续视图将正确生成。但是,当我点击触发POST的Submit按钮(打印出上面的内容)时,我得到了以下错误:

Page not found (404)
"/Users/a/Documents/websites/website/ipsych/processed" does not exist
Request Method: GET
Request URL:    http://localhost:8000/ipsych/processed//
Raised by:  django.views.static.serve

为什么ipsychcase_id会丢失?

qco9c6ql

qco9c6ql1#

在更改window.location.href之前打印出url。{{ipsychcase_id}}不存在。
为什么不使用django的{% url 'app:view' %}模板函数?

success: function(response) {
    window.location.href = "{% url 'ipsych_results' ipsychcase_id %}";
},

这可能是因为视图中的窗体无效;你不把身份证还给我但也不处理任何错误。

dzjeubhm

dzjeubhm2#

只是为了添加到@nigel329的答案
return JsonResponse({"ipsychcase_id": ipsychvisit_instance.ipsychvisit_id})所需的初始视图的后置功能
这可以通过 AJAX 代码访问为:

success: function(response) {
                    var ipsychcase_id = response.ipsychcase_id
                    window.location.href = '/ipsych/processed/' + ipsychcase_id + '/';
                },

相关问题