You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django中BSModalCreateView忽略get_success_url问题求助

Fixing get_success_url() Ignored in BSModalCreateView

I see your issue—this is a common gotcha with BSModalCreateView from django-bootstrap-modal-forms! The problem stems from how this class handles AJAX-powered modal forms. Let me break it down and show you how to fix it.

Why Your Current Code Isn't Working

BSModalCreateView is built for AJAX submissions by default. When you override form_valid() and return a HttpResponseRedirect, the AJAX request receives this redirect, but the frontend JavaScript from the bootstrap modal forms library doesn’t process it like a regular page request. Instead, it expects a JSON response containing a success_url field to handle the redirect client-side. Your manual redirect gets ignored because it’s not in the format the library expects.

The Fix: Let the Parent Class Handle the Response

Instead of returning HttpResponseRedirect directly, call the parent class’s form_valid() method (which constructs the proper JSON response) and ensure your get_success_url() is correctly used. Here’s how to adjust your code:

class SignUpView(BSModalCreateView):
    model = User
    form_class = SignUpForm
    success_message = 'Please check your email to complete the registration'
    template_name = 'form_modal.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['heading'] = 'Create ID'
        return context

    def form_valid(self, form):
        # Your custom user creation and email logic stays intact
        user = form.save(commit=False)
        user.is_active = False
        user.save()
        
        current_site = '127.0.0.1:8000'
        mail_subject = 'Activate your account.'
        message = render_to_string('registration/confirm_email.html', {
            'user': user,
            'domain': '127.0.0.1:8000',
            'uid': urlsafe_base64_encode(force_bytes(user.pk)),
            'token': default_token_generator.make_token(user),
        })
        to_email = form.cleaned_data.get('email')
        email = EmailMessage(
            mail_subject, message, to=[to_email]
        )
        email.send()

        # Call parent class's form_valid to generate the correct JSON response
        response = super().form_valid(form)
        # Parent class automatically uses your get_success_url() here—no extra setup needed
        return response

    def get_success_url(self):
        return reverse('dashboard')

Additional Checks

  • Frontend JavaScript: Make sure you’ve included the django-bootstrap-modal-forms JS and initialized your modal correctly. The library relies on this JS to read the success_url from the JSON response and trigger the redirect. Example initialization:
    $(document).ready(function() {
        $("#your-modal-form-id").modalForm({
            formURL: "{% url 'signup' %}"
        });
    });
    
  • AJAX Setup Confirmation: Ensure your form has the proper ajax class or data attributes to trigger AJAX submission. If the form bypasses AJAX, the redirect logic won’t work as expected.

Why This Works

The parent BSModalCreateView.form_valid() method builds a JSON response that includes your success_message and the URL from get_success_url(). The frontend JS detects this response and redirects the user to your specified dashboard URL, which is exactly what you want.

内容的提问来源于stack exchange,提问作者HobbyHack

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 19:42:40