jazzband / django-smart-selects

chained and grouped selects for django forms
https://django-smart-selects.readthedocs.io/
BSD 3-Clause "New" or "Revised" License
1.11k stars 348 forks source link

Using smart-selects in edit form first shows results, then quickly resets to "Choose county" and "Choose municipality" #231

Closed josefnorlin closed 3 years ago

josefnorlin commented 6 years ago

You MUST use this template when reporting issues. Please make sure you follow the checklist and fill in all of the information sections below.


All versions of django-smart-selects prior to version 1.2.8 are vulnerable to an XSS attack as detailed in issue 171. As a result, all previous versions have been removed from PyPI to prevent users from installing insecure versions. All users are urged to upgrade as soon as possible.

Checklist

Put an x in the bracket when you have completed each task, like this: [x]

Steps to reproduce

  1. Create an edit form using chained selects

Actual behavior

Add form works seamlessly. But when using edit with the same form and smart selects the values from the database gets loaded but then resets to "Choose county" and "Choose municipality".

Expected behavior

The posts value for 'county' and 'municipality' stays to what they are set to in the database.

Here's my code:

models.py

class Poster(models.Model):
    title = models.CharField(max_length=100)
    county = ChainedForeignKey(
        'locations.County',
        chained_field="country",
        chained_model_field="country",
        show_all=False,
        auto_choose=True,
        sort=True)
    municipality = ChainedForeignKey(
        'locations.Municipality',
        chained_field="county",
        chained_model_field="county",
        show_all=False,
        auto_choose=True,
        sort=True)
    address = models.CharField(max_length=100, null=True, blank=True)

views.py

@login_required
def add(request):
    if request.method == "POST":
        form = PosterForm(request.POST, request.FILES)
        if form.is_valid():
            post = form.save(commit=False)
            post.owner = request.user
            post.creation_date = timezone.now()
            post.save()
            return redirect('/my_posters', pk=post.pk)
    else:
        form = PosterForm()
    return render(request, 'posters/edit.html', {'form': form})

@login_required
def poster_edit(request, pk):
    post = get_object_or_404(Poster, pk=pk)
    if request.method == "POST":
        form = PosterForm(request.POST or None, request.FILES or None, instance=post)
        if form.is_valid():
            post = form.save(commit=False)
            post.owner = request.user
            post.creation_date = timezone.now()
            post.save()
            return redirect('/my_posters', pk=post.pk)
    else:
        form = PosterForm(instance=post)
    return render(request, 'posters/edit.html', {'form': form})

forms.py

class PosterForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(PosterForm, self).__init__(*args, **kwargs)
        self.fields['category'].empty_label = 'Välj kategori'
        self.fields['county'].empty_label = 'Välj län'
        self.fields['municipality'].empty_label = 'Välj område'

    class Meta:
        model = Poster
        fields = ('title', 'county', 'municipality', 'address')

        labels = {
                    "title": "Rubrik",
                    "county": "Län",
                    "municipality": "Område",
                }

        widgets = {
                'title' : forms.TextInput(attrs={'name' : 'title', 'placeholder':'Rubrik', 'class': 'form-control'}),
                'county': forms.Select(attrs={'name' : 'county', 'class': 'form-control chained' }),
                'municipality': forms.Select(attrs={'name' : 'municipality', 'class': 'form-control chained' }),
                'address' : forms.TextInput(attrs={'name' : 'address', 'placeholder':'Valfritt: Adress', 'class': 'form-control'}),                
        }

edit.html

<div class="col-md-8">
    <div class="col-md-6" style="padding: 0;">
        {{ form.county }}
    </div>
    <div class="col-md-6" style="padding: 0;">
        {{ form.municipality }}
    </div>
    {{ form.address }}
</div>

<script>
    (function($) {
        var chainfield = "#id_country";
        var url = "/chaining/filter/locations/County/country/posters/Poster/county";
        var id = "#id_county";
        var value = undefined;
        var auto_choose = true;
        var empty_label = "Välj län";

        $(document).ready(function() {
            chainedfk.init(chainfield, url, id, value, empty_label, auto_choose);
        });
    })(jQuery || django.jQuery);

    (function($) {
        var chainfield = "#id_county";
        var url = "/chaining/filter/locations/Municipality/county/posters/Poster/municipality";
        var id = "#id_municipality";
        var value = undefined;
        var auto_choose = true;
        var empty_label = "Välj område";

        $(document).ready(function() {
            chainedfk.init(chainfield, url, id, value, empty_label, auto_choose);
        });
    })(jQuery || django.jQuery);
</script>
openrijal commented 6 years ago

@tuxedojoe these PRs should fix it https://github.com/digi604/django-smart-selects/pull/260 and https://github.com/digi604/django-smart-selects/pull/259 cc: @blag

manelclos commented 4 years ago

@josefnorlin can you reproduce with latest master version?

manelclos commented 3 years ago

Closing due to inactivity