Arbazz Hussain
Arbazz Hussain

Reputation: 1932

filling django forms based on choice with models data as initial data

Need help regarding adding model class fields as initial data to our forms data.

models.py

class SourceCode(models.Model):
    source_description = models.CharField(max_length=80,unique=True)
    source_urls = ArrayField(ArrayField(models.TextField(blank=True),),blank=True,null=True)
    source_results = JSONField(blank=True,null=True)

    def __str__(self):
        return self.source_description

forms.py

class SourceForm(forms.Form):
    source_description = forms.ModelChoiceField(queryset=SourceCode.objects.all(),required=True)
    source_form_urls = forms.CharField(widget=forms.Textarea(attrs={'placeholder':'Enter URLS Here'}))

I had created Source1 object & added https://stackoverflow.com value in source_urls field.

enter image description here


Here's how it looks like:

As soon as i select Source1 from forms.ModelChoiceField, i want it to show the source_urls field data of source_urls based on object selected by user.

enter image description here

Upvotes: 0

Views: 264

Answers (1)

BottleZero
BottleZero

Reputation: 983

Sounds like a JavaScript solution is needed.

You could either load all source_urls in the template after setting a context variable called 'source_urls' in your views context:

Your view:

class YourViewName():

    def get_context_data(self, **kwargs):
        context_data = super().get_context_data(**kwargs)
        context_data['source_urls'] = SourceCode.objects.values('id', 'source_urls')
        return context_data

In template:

<script>
    var source_urls = {
        {% for su in source_urls %}
        "{{ su.id }}": "{{ su.source_urls }}",
        {% endfor %}
    }
</script>

Then add something to your JavaScript:

$('#source_description_id').change(function() {
    $('#source_form_urls_id').val(source_urls[$(this).val()]);
});

Or you could create another view that searches for the source_urls with an ajax call:

def source_url_searcher(request):

    source_id = request.GET.get('id')
    source_urls = SourceCode.objects.get(id=source_id).source_urls 

    return return JsonResponse({source_urls: source_urls})

And your JavaScript:

$('#source_description_id').change(function() {
    $.ajax({
        url: <the_ajax_url>,
        data: {source_id: $(this).val()},
        success: function(response) {
            $('#source_form_urls_id').val(response.source_urls);
        }
    });
});

Either example would need some polishing to work correctly, but they provide the general idea.

Upvotes: 2

Related Questions