alexa
Facebook
Twitter
LinkedIn
Instagram
Whatsapp
Call Now
Quick Inquiry

Auto-submit django form without causing infinite loop in python

Auto-submit django form without causing infinite loop in python

The general practice for this type of situation is to only use the post method for validating and saving the submission, and then automatically reloading the page.

Javascript isn't required, so you can remove it from your template.

I have modified your UserCurrency model to use a OneToOneField relationship with the User. This means that there can be no more than one of these records per User. It also means that you can access the saved currency directly from the user instance.

I have also set a default currency of 'USD'. In the view, the try/except block creates a temporary UserCurrency instance when one doesn't already exist.

MODEL

 class UserCurrency(models.Model):
    user = models.OneToOneField(
        User,
        primary_key=True,
        related_name="user_currency",
        on_delete=models.CASCADE)
    currency = models.CharField(max_length=10, default="USD") 

VIEW

 from django.http import HttpResponseRedirect

class MyDashboardView(TemplateView):
    template_name = 'coinprices/my-dashboard.html'

    def get_context_data(self, **kwargs):
        """
        Add the saved currency, deposit and form to the context. 
        This is then available for both get and post methods.

        """
        try:
            user_currency = self.request.user.user_currency
        except UserCurrency.DoesNotExist:
            user_currency = UserCurrency(user=self.request.user)
        
        rates = {'USD': 1.0, 'AUD': 1.321, 'GBP': 0.764, 'CAD': 1.249}

        context = super().get_context_data(**kwargs)
        context['user_currency'] = user_currency
        context['deposit'] = 10000 / rates[user_currency.currency]
        context['form_c'] = CurrencyForm(instance=user_currency, prefix='form_c')
        return context

    def post(self, request, *args, **kwargs):
        """
        If valid, save/update the model instance and reload the page.
        Otherwise, display the form with errors.

        """
        context = self.get_context_data(**kwargs)
        form_c = CurrencyForm(request.POST, instance=context['user_currency'], prefix='form_c')
        
        if form_c.is_valid():
            form_c.save()
            return HttpResponseRedirect(request.path_info)

        context['form_c'] = form_c
        return self.render_to_response(context)

20 0
7

Write a Comments


* Be the first to Make Comment

GoodFirms Badge
GoodFirms Badge

Fix Your Meeting With Our SEO Consultants in India To Grow Your Business Online