选中Django中选中的项目复选框

时间:2017-07-03 07:10:42

标签: python django checkbox django-forms django-views

我正在研究一个观点。我正在尝试创建一个html文件,它将显示基于记录模型的表单。在html文件中,我添加了代码,该代码将显示该组的所有成员。每个成员旁边都有一个复选框。在view.py文件中,我想浏览每个成员,如果选中该复选框,我想创建一个新的transacition对象,并在事先检查时将其保存到数据库中。我收到错误,看起来像这样......

ERROR:

KeyError at /23/addRecord/
'omar'
Request Method: POST
Request URL:    http://127.0.0.1:8000/23/addRecord/
Django Version: 1.8.6
Exception Type: KeyError
Exception Value:    
'omar'
Exception Location: C:\Users\OmarJandali\Desktop\opentab\opentab\tab\views.py in addRecord, line 237
Python Executable:  C:\Users\OmarJandali\AppData\Local\Programs\Python\Python36\python.exe
Python Version: 3.6.1
Python Path:    
['C:\\Users\\OmarJandali\\Desktop\\opentab\\opentab',
 'C:\\Users\\OmarJandali\\AppData\\Local\\Programs\\Python\\Python36\\python36.zip',
 'C:\\Users\\OmarJandali\\AppData\\Local\\Programs\\Python\\Python36\\DLLs',
 'C:\\Users\\OmarJandali\\AppData\\Local\\Programs\\Python\\Python36\\lib',
 'C:\\Users\\OmarJandali\\AppData\\Local\\Programs\\Python\\Python36',
 'C:\\Users\\OmarJandali\\AppData\\Local\\Programs\\Python\\Python36\\lib\\site-packages']
Server time:    Mon, 3 Jul 2017 07:02:20 +0000
Traceback Switch to copy-and-paste view

C:\Users\OmarJandali\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py in get_response
                                response = wrapped_callback(request, *callback_args, **callback_kwargs) ...
▶ Local vars
C:\Users\OmarJandali\Desktop\opentab\opentab\tab\views.py in addRecord
                            username = cd[member.user.username] ...
▶ Local vars
Request information

GET
No GET data
POST
Variable    Value
csrfmiddlewaretoken 
'vIg5KKWVNpoc2ijkwmBB9I28aDt7QOSA'
split   
'2'
omar    
'checked'
hani    
'checked'
submit  
'submit'

以下是我现在拥有的文件。

view.py

def addRecord(request, groupId):
    # for the records, the user and group need to be provided to know what group
    # this record is attached to and who created the record.
    user = User.objects.get(username='omar')
    group = Group.objects.get(id=groupId)
    members = Member.objects.filter(group=groupId)
    # the followin process is similar to the form validation for the group view.
    if request.method == 'POST':
        message = 'process'
        form = AddRecordForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            split = cd['split']
            new_record = Record.objects.create(
                split = split,
                status = 1,
                group = group,
                user = user,
            )
            for member in members:
            if member.user.username in request.GET:
                new_transaction = Transaction.objects.create(
                    amount = 0.00,
                    description = 'description',
                    group = group,
                    user = member,
                    record = new_record,
                )
        return redirect('accounts')
    else:
        # the only tyhing that needed to be passed was the group to display the naem
        # and the form that is going to be used and filled out by the user and submitted
        form = AddRecordForm()
        message = 'no processing'
        params = {
            'group':group,
            'members':members,
            'form':form,
            'message':message,
        }
    return render(request, 'tabs/add_record.html', params)

html文件:

{% extends "base.html" %}

{% block content %}
  <h2>add record to {{ group.name }}</h2>
  {% if message %}
    <p>{{message}}</p>
  {% endif %}
  <form action="." method="POST">
    {% csrf_token %}
    {{ form.as_p }}
    {% for member in members %}
      {{ member.user.username }}
      <input name="{{member.user.username}}" value="checked" type="checkbox"><br>
    {% endfor %}
    <input type="submit" name="submit" value="submit">
  </form>
{% endblock %}

models.py文件

class Record(models.Model):
    split = models.SmallIntegerField(default=1) #user
    count = models.IntegerField(default=1)
    status = models.SmallIntegerField(choices=RECORD_STATUS_CHOICES, default=1) #server
    group = models.ForeignKey(Group, default=1, on_delete=models.CASCADE) #server
    user = models.ForeignKey(User, default=1, on_delete=models.CASCADE) #server
    created = models.DateTimeField(auto_now_add=True) #server

class Transaction(models.Model):
    amount = models.DecimalField(decimal_places=2, max_digits=9,default=0.00)
    description = models.CharField(max_length=250)
    group = models.ForeignKey(Group, default=1, on_delete=models.CASCADE)
    user = models.ForeignKey(User, default=1, on_delete=models.CASCADE)
    record = models.ForeignKey(Record, default=1, on_delete=models.CASCADE)
    created = models.DateTimeField(auto_now_add=True)

我尝试过做一些不同的事情,包括改变表单输入名称和值。我尝试了几种不同的方法来改变cd []内容以及如何检查它是否存在错误发生的位置。任何人都可以帮我解决这个棘手的问题。

1 个答案:

答案 0 :(得分:1)

您在request.GET 中收到错误
相反,

    if member.user.username in request.POST: