如何在Django中从列表中删除一个值

gr8qqesn  于 2023-03-24  发布在  Go
关注(0)|答案(1)|浏览(152)

我是Django和查询集的新手。当用户按下删除按钮时,我试图删除一列。
我有用户模型和usecase_assign,我试图执行这个方法:从usecase_assign删除其中usecase_assign. user_email = 'nmubarak.c';
如何从模板中获取user_email并将其传递到视图中以删除它?
我尝试的错误:精确查找的QuerySet值必须使用切片限制为一个结果。Django
我的usecase_assign模型:

class UsecaseAssign(models.Model):
    usecase_assign_date = models.DateTimeField(primary_key=True, auto_now_add=True)
    usecase = models.ForeignKey(Usecase, models.DO_NOTHING)
    user_email = models.ForeignKey('User', models.DO_NOTHING, db_column='user_email')
    usecase_role_id = models.CharField(max_length=20)

我的看法是相当长的第一部分得到的用户列表和分配新的,第二次它取消分配用户

def view_usecase_details(request, ucid, eid):
    usecase_details = Usecase.objects.filter(usecase_id=ucid).all()
    usecase_details = usecase_details.prefetch_related("usecaseids")
    users = User.objects.all() #SELECT user_email FROM usecase_assign WHERE usecase_id LIKE 'NN245';
    usecase_assigned = UsecaseAssign.objects.select_related('user_email').values_list('user_email__user_name').filter(usecase_id=ucid) #to show list of users working on uc
    if request.method=='POST' and 'assignuser' in request.POST:
        user_email = request.POST['user_email']
        userAssignCheck = UsecaseAssign.objects.filter(user_email=user_email, usecase_id=ucid)
        if userAssignCheck:
            messages.error(request, "user already added!")
            return HttpResponseRedirect(reverse('usecase-details', args=[ucid, eid]))
        else:
            userAssignObj = UsecaseAssign.objects.create(user_email_id=user_email, usecase_id=ucid)

        if userAssignObj:    
            messages.success(request, "User was Successfully Assigned with Usecase!")
            return HttpResponseRedirect(reverse('usecase-details', args=[ucid, eid]))
    
    if request.method=='POST' and 'delete_user' in request.POST:
        #DELETE FROM `usecase_assign` WHERE `usecase_assign`.`user_email` = 'nmubarak.c';
        users = User.objects.filter(user_email=request.user)    
        assign_date = UsecaseAssign.objects.filter(user_email=users).values_list('usecase_assign_date')
        assigned_user = UsecaseAssign.objects.filter(usecase_assign_date=assign_date).delete()
        if assigned_user:
            messages.success(request, "user was deleted successfully!")
            return HttpResponseRedirect(reverse('usecase-details', args=[ucid, eid]))
        else:
            messages.error(request, "Some Error was occurred!")
            return HttpResponseRedirect(reverse('usecase-details', args=[ucid, eid]))
            

    context = {'usecase_details': usecase_details, "users": User.objects.all(), 'usecase_assigned':usecase_assigned, "users": users}
    return render(request, 'UsecaseDetails.html', context)

我的模板:

{% for result in usecase_details %}
<div class="card card-body shadow-sm mb-4 mb-lg-0">
    <form class="mb-card" action="/usecase-details/{{result.usecase_id}}/{{result.user_email}}/" method="POST">
        {% csrf_token %}
        <div class="form-row mb-4">
          <div class="col-lg-8 mr-f">
            <label class="h5" for="user_email">Assign new users:</label>
            <select name="user_email" class="custom-select my-1 mr-sm-2" id="user">
                <option value="0" selected>Select</option>
                {% for user in users %}
                <option value="{{ user.user_email }}">{{ user.user_name }}</option>
                {% endfor %}                             
              </select>    
            </div>
        </div>
        <input type="submit" class="btn btn-primary" name="assignuser" value="Submit Changes">
      </form>
      <ul class="list-group list-group-flush">
        <li class="list-group-item d-flex align-items-center justify-content-between px-0 border-bottom">
            <div>
                <label class="mb-card h5" for="user_email">Assigned users:</label>
            {% for user in usecase_assigned %}
            <form action="/usecase-details/{{result.usecase_id}}/{{result.user_email}}/" method="POST" style="display: inline !important;">
                {% csrf_token %}
            <div class="btn-group me-2 mb-2">
                <button type="button" class="btn btn-outline-danger">{{user|join:', '}}</button>
                <button type="submit" class="btn btn-danger" name="delete_user">
                    <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-file-x-fill" viewBox="0 0 16 16">
                        <path d="M12 0H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V2a2 2 0 0 0-2-2zM6.854 6.146 8 7.293l1.146-1.147a.5.5 0 1 1 .708.708L8.707 8l1.147 1.146a.5.5 0 0 1-.708.708L8 8.707 6.854 9.854a.5.5 0 0 1-.708-.708L7.293 8 6.146 6.854a.5.5 0 1 1 .708-.708z"></path>
                      </svg>                   
                </button>
              </form>
            </div>
            {% endfor %}  

            </form>
            </div>          
        </li>
    </ul>
</div>
{% endfor %}

我正在尝试允许用户删除取消分配用户,如下所示:

ktecyv1j

ktecyv1j1#

你会得到这个错误,因为你试图直接将值queryset传递给过滤器函数。这两种方式都没有意义。因此,你应该首先修复你想要删除的用户ID,并将其传递到视图中进行删除。你可以这样尝试:

// HTML
<label class="mb-card h5" for="user_email">Assigned users:</label>
    {% for user in usecase_assigned %}
    <form action="/usecase-details/{{result.usecase_id}}/{{user.id}}/" method="POST" style=...>
    {% csrf_token %}
<div class="btn-group me-2 mb-2">
    <button type="button" class="btn btn-outline-danger">{{user|join:', '}}</button>
    <button type="submit" class="btn btn-danger" name="delete_user">
        <svg ...></path>
          </svg>                    
    </button>
  </form>
</div>
{% endfor %}

然后更新您的URL并查看如下内容:

# url
urlpatterns = [
    path('/usecase-details/<int:ucid>/<int:user_id>/', views.someview)
 
# view
def someview(request, ucid, user_id):
    if request.method=='POST' and 'delete_user' in request.POST:    
           assigned_user = UsecaseAssign.objects.filter(user_email_id=user_id, id=ucid).delete()
           if assigned_user:
                messages.success(request, "user was deleted successfully!")
                return HttpResponseRedirect(reverse('usecase-details', args=[ucid]))
           else:
                messages.error(request, "Some Error was occurred!")
                return HttpResponseRedirect(reverse('usecase-details', args=[ucid]))

相关问题