许多对许多django领域没有储蓄

时间:2017-07-05 17:10:27

标签: python django many-to-many django-autocomplete-light

我正在尝试将表单数据存储到模型中,当用户提交表单时,除了显示为ShoeApp.Shoe.None的多对多字段(鞋子)之外,所有数据都被正确保存,有人可以请帮我编辑我的视图,以便保存这些信息?提前谢谢。

models.py:

class Shoe(models.Model):
    """
    Stores shoes for use in app
    """
    symbol = models.CharField(max_length=32)
    aliases = ArrayField(models.CharField(max_length=16, blank=True), blank=True, null=True)
    description = models.CharField(max_length=512, blank=True)
    ensembl_id = models.CharField(max_length=32, blank=True)

    def get_absolute_url(self):
        return reverse('shoelist')

    def __str__(self):
        return self.symbol

    class Meta:
        ordering = ('symbol',)

class ShoeList(models.Model):
    """
    A list of shoes that can be selected 
    """
    name = models.CharField(max_length = 256)
    created_by  = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
    description = models.CharField(max_length = 512)
    notes = models.TextField()
    shoes = models.ManyToManyField(Shoe)
    public = models.BooleanField(default = False)

    def get_absolute_url(self):
        return reverse('shoelistlists', kwargs={'pk': self.pk})

forms.py:

    class ShoeListCreateForm(forms.ModelForm):

        shoes = forms.ModelMultipleChoiceField(

            queryset=Shoe.objects.all(),
            widget=autocomplete.ModelSelect2Multiple(url='shoelist-autocomplete')
        )

        class Meta:
            model= ShoeList
            fields = ['name', 'description', 'notes', 'shoes', 'public']

views.py

class ShoeListAutocomplete(autocomplete.Select2QuerySetView):
    def get_queryset(self):
        if not self.request.user.is_authenticated():
            return Shoe.objects.none()

        qs = Shoe.objects.all()

        if self.q:
            qs = qs.filter(symbol__istartswith=self.q)

        return qs


class ShoeListCreateView(CreateView):
    form_class = ShoeListCreateForm
    model = ShoeList

    def form_valid(self, form):
        # print('form is valid')
        # print(form.data)

        obj = form.save(commit=False)
        obj.created_by = self.request.user
        obj.save()
        return HttpResponseRedirect(reverse('genelistlists'))

shoelist_form.html

{% extends "base_form.html" %}
{% load static %}



{% block form_block %}
{{ block.super }}
<table class="table">
<thead>
<tr><th width="25%"></th><th></th></tr>
</thead>
<tbody>
<form action="" method="post">{% csrf_token %}
{{ form.as_table }}
</tbody>
</table>
<input class="btn btn-primary" type="submit" value="Create"/>&nbsp;&nbsp;
</form>

{% endblock %}

{#for django-autocomplete-light#}
{% block footer %}
<script type="text/javascript" src="{% static 'admin/js/vendor/jquery/jquery.js' %}"></script>

{{ form.media }}

{% endblock %}

0 个答案:

没有答案