迁移后数据未正确保存

时间:2019-05-09 05:55:19

标签: django django-models django-mptt

我正在使用django的最新版本django-mptt。这是先前状态的模型:

shop_options = (
    ('grocery', _('Grocery')),
    ('medicine', _('Medicine')),
    ('electronics', _('Electronics')),
    ('fashion', _('Fashion')),
    ('garden', _('Garden')),
    ('gift', _('Gift')),
)


class Category(MPTTModel):
    name = models.CharField(max_length=50, unique=True)
    name_bn = models.CharField(max_length=50, unique=True)
    active = models.BooleanField(default=True)
    parent = TreeForeignKey('self', null=True, blank=True, related_name='children',
                            db_index=True, on_delete=models.PROTECT)
    slug = models.SlugField(max_length=200, db_index=True)
    shop_type = models.CharField(choices=shop_options, max_length=40)

    class MPTTMeta:
        order_insertion_by = ['name']

    class Meta:
        unique_together = ('parent', 'slug',)
        verbose_name_plural = 'categories'

    def save(self, *args, **kwargs):
        if not self.id:
            # Newly created object, so set slug
            self.slug = slugify(self.name)

        super(Category, self).save(*args, **kwargs)

此时一切正常。然后我又添加了两个shop_options

shop_options = (
    ('grocery', _('Grocery')),
    ('medicine', _('Medicine')),
    ('electronics', _('Electronics')),
    ('fashion', _('Fashion')),
    ('garden', _('Garden')),
    ('gift', _('Gift')),
    ('baby_care', _('Baby Care')),
    ('pet_care', _('Pet Care')),
)

然后生成迁移并成功迁移此更改。现在,当我想将先前保存的类别对象从grocery / fashion(任何内容)更改为baby_carepet_care时,它将另存为gift

这是自动生成的迁移文件:

# Generated by Django 2.2.1 on 2019-05-08 17:12

from django.db import migrations, models


class Migration(migrations.Migration):

    dependencies = [
        ('shop', '0074_auto_20190425_2236'),
    ]

    operations = [
        migrations.AlterField(
            model_name='category',
            name='shop_type',
            field=models.CharField(choices=[('index', 'Index'), ('grocery', 'Grocery'), ('medicine', 'Medicine'), ('electronics', 'Electronics'), ('fashion', 'Fashion'), ('garden', 'Garden'), ('gift', 'Gift'), ('baby_care', 'Baby Care'), ('pet_care', 'Pet Care')], max_length=40),
        ),
        migrations.AlterField(
            model_name='product',
            name='shop_type',
            field=models.CharField(choices=[('index', 'Index'), ('grocery', 'Grocery'), ('medicine', 'Medicine'), ('electronics', 'Electronics'), ('fashion', 'Fashion'), ('garden', 'Garden'), ('gift', 'Gift'), ('baby_care', 'Baby Care'), ('pet_care', 'Pet Care')], max_length=40),
        ),

   /// some other related models
    ]

此问题还导致与Category模型(例如产品模型)相关的其他模型出现相同的问题。

这是更改类别对象的视图:

def category_edit(request, pk):
    cat = get_object_or_404(Category, pk=pk)
    if request.method == 'POST':
        category = CategoryForm(request.POST, instance=cat)
        try:
            parent = Category.objects.get(name=request.POST.get('parent'))
        except Category.DoesNotExist:
            parent = None
        if category.is_valid():
            category_obj = category.save(commit=False)
            category_obj.parent = parent
            category_obj.save()
            messages.success(request, 'Category has been updated ')
        else:
            messages.warning(request, category.errors)
        return redirect('category_create')
    parent = Category.objects.filter(parent=None)
    return render(request, 'admin/category/category_edit.html', {'category_list': 'active', 'parent': parent,
                                                                 'category': cat, 'header': 'Edit Category'})

CategoryForm代码:

class CategoryForm(ModelForm):
    class Meta:
        model = Category
        exclude = ('parent', 'slug')

category_edit.html:

{% extends 'admin/base.html' %}
{% block content %}
    <div class="content">
        <div class="card">
            <div class="card-header">
                <h3>{{ header }}</h3>
            </div>
            <div class="card-body">
                {% if messages %}
                    {%for message in messages %}
                        <div class="alert alert-{{ message.tags }}" role="alert">
                            <ul class="messages">
                                <li class="text-center">{{ message }}</li>
                            </ul>
                        </div>
                    {% endfor %}
                {% endif %}
                <form action="{% url 'category_edit' pk=category.pk %}" method="post"> {% csrf_token %}
                    <div class="form-group">
                        <label>Name</label>
                        <input type="text" name="name" value="{{ category.name }}" class="form-control form-control-lg" placeholder="Enter category name" required>
                    </div>
                    <div class="form-group">
                        <label>Name Bengali</label>
                        <input type="text" name="name_bn" value="{{ category.name_bn }}" class="form-control form-control-lg" placeholder="Enter category name in bengali">
                    </div>
                    <div class="form-group">
                        <label>Shop Type</label>
                        <select name="shop_type" class="form-control form-control-lg" required>
                            <option value="grocery" {% if category.shop_type == 'grocery' %}selected {% endif %}>Grocery</option>
                            <option value="medicine" {% if category.shop_type == 'medicine' %}selected {% endif %} >Medicine</option>
                            <option value="electronics" {% if category.shop_type == 'electronics' %}selected {% endif %} >Electronics</option>
                            <option value="fashion" {% if category.shop_type == 'fashion' %}selected {% endif %} >Fashion</option>
                            <option value="garden" {% if category.shop_type == 'garden' %}selected {% endif %} >Garden</option>
                            <option value="gift" {% if category.shop_type == 'gift' %}selected {% endif %} >Gift</option>
                            <option value="gift" {% if category.shop_type == 'baby_care' %}selected {% endif %} >Baby Care</option>
                            <option value="gift" {% if category.shop_type == 'pet_care' %}selected {% endif %} >Pet Care</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label><strong>Active</strong></label>
                        <select name="active" class="form-control form-control-lg" required>
                            <option value="True" {% if category.active %} selected {% endif %}>Yes</option>
                            <option value="False" {% if not category.active %} selected {% endif %}>No</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Parent Category (If it is a sub category)</label>
                        <select name="parent" class="form-control selectpicker"  data-live-search="true" >
                            <option {% if category.parent == 'None' %}selected {% endif %}>None selected</option>
                            {% for hiren in parent %}
                                <option value="{{ hiren.name }}" {% if category.parent.name == hiren.name %} selected {% endif %} >{{ hiren.name }}</option>
                            {% endfor %}
                        </select>
                    </div>
                    <button type="submit" class="btn btn-primary">Save</button>
                </form>
            </div>
        </div>
    </div>
{% endblock %}

1 个答案:

答案 0 :(得分:1)

一种稍微系统化的方法:

<select name="shop_type" class="form-control form-control-lg" required>
    {% for key, value in shop_options %}
        <option value="{{ key }}" {% if category.shop_type == key %}selected {% endif %}>{{ value }}</option>
    {% endfor %}

并将shop_options传递到模板。