我正在尝试这样做:在我的网站上,我有一些来自数据库的数据,如下所示:
Math 140
Math 141
CS 320
CS 240
我想这样做:当你复选框而不是按删除时,该主题会从数据库中删除。
Math 140 []
Math 141 []
CS 320 []
CS 240 []
template.html
<div id="subjects-list">
{% if user.username %}
<ul>
{% if subjects %}
{% for subject in subjects %}
<li>{{ subject.name }}
{% endfor %}
{% else %}
No Subjects for this user
{% endif %}
</ul>
{% else %}
You are in else
{% endif %}
</div>
models.py
class Subjects(models.Model):
""" Subject Database """
name = models.CharField(max_length=64, unique=False) #Subject Names on left-menu
user = models.ForeignKey(User, unique=False)
def __unicode__(self):
return '%s %s' %(self.name, self.user.username)
views.py
@login_required
def user_page(request, username):
user = get_object_or_404(User, username=username)
''' Form in the left-menu to create a new subject '''
if 'subject-create-b' in request.POST:
subject_form = SubjectCreationForm(request.POST)
if subject_form.is_valid():
subject = Subjects.objects.get_or_create(name = subject_form.data['name'],
user = user)
return HttpResponseRedirect('.') # redirect to the same page
# later have to be substituted with AJAX
else:
subject_form = SubjectCreationForm()
# Filter Subjects table by currently logged in user
subjects = Subjects.objects.filter(user__exact = user)
return render_to_response('user_page.html',
{'subject_creation_form': subject_form,
'subjects': subjects,
'user': request.user,
},
context_instance=RequestContext(request))
所以我的问题基本上是怎么做到的?
我是否需要添加新表单,而不是在“
或者我是否需要向mymodel添加一些新列,并且如果选中复选框,则将此列切换为true,而在视图中删除所有在新列中为true的行。
或者你可以建议一些更好的技术。 提前谢谢!
答案 0 :(得分:0)
您忘记列出表单的代码。
您可以将MultipleChoiceField与'choices'一起用作您的查询集,并使用CheckboxSelectMultiple小部件列出带有复选框的课程。然后,您可以从表单中获取要删除的课程。