Django匹配错误与选择字段

时间:2018-04-18 13:36:45

标签: python django django-models django-views

urls.py

path('preferences/<action>/<category>/', views.preferences),

HTML表单

            <form method="post">
                {% csrf_token %}
                {% for field in location_form %}
                    {{ field.label_tag }}<br>
                    {{ field }}
                    {% for error in field.errors %}
                        <p style="color: red">{{ error }}</p>
                    {% endfor %}
                {% endfor %}
                <button type="submit" formaction="/wheelwatch/preferences/save/location/">Save</button>
                <button type="submit" formaction="/wheelwatch/preferences/delete/location/">Delete</button>
            </form>

views.py

    elif action == 'delete':

        if category == 'location':
            # match form data to CLLocation's location field
            location_url = request.POST['location']
            location_list = CLLocation._meta.get_field('location').choices

            for location in location_list:

                if location[0] == location_url:
                    CLLocation.objects.get(location=location[1], user__username=request.user).delete()

我收到的“匹配查询不存在错误”。我知道数据库中有一个对象具有匹配的“用户”和“位置”字段,但我无法正确访问和删除它!

models.py

class CLLocation(models.Model):

    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    location_choices = (
        ('https://auburn.craigslist.org/', 'AL - auburn'),
        ...
    location = MultiSelectField(choices=location_choices)

2 个答案:

答案 0 :(得分:0)

我认为问题是您删除的语法。

您正在混合两种不同的解决方案:获取实例,然后直接删除或删除。尝试其中之一:

instance = CLLocation.objects.get(location=location[1], user__username=request.user)
instance.delete()

CLLocation.objects.filter(location=location[1], user__username=request.user).delete()

请参阅django help here

答案 1 :(得分:0)

只需在删除查询中进行更改,如下所示:

CLLocation.objects.get(location=location[1], user=request.user).delete()

因为用户本身是AuthUser的外键,所以你只需要提供authuser对象作为参数。