我创建了一个问题应用,可以从管理员中添加问题。有一个布尔字段,名为is_mcq
。
这是我的模型:
from django.db import models
from datetime import datetime
from languages.models import Language
from languageversions.models import Languageversion
from experiences.models import Experience
from difficulties.models import Difficulty
class Question(models.Model):
language = models.ForeignKey(Language, on_delete=models.DO_NOTHING)
version = models.ForeignKey(Languageversion, on_delete=models.DO_NOTHING)
experience = models.ForeignKey(Experience, on_delete=models.DO_NOTHING)
difficulty = models.ForeignKey(Difficulty, on_delete=models.DO_NOTHING)
title = models.CharField(max_length=200)
question = models.TextField(blank=False)
answer = models.TextField(blank=False)
is_mcq = models.BooleanField(default=False )
mcq_answer = models.TextField(blank=True)
mcq_answer1 = models.TextField(blank=True)
mcq_answer2 = models.TextField(blank=True)
mcq_answer3 = models.TextField(blank=True)
attachment = models.FileField(upload_to='photos/%Y/%m/%d/', blank=True)
list_date = models.DateTimeField(default=datetime.now, blank=True)
def __str__(self):
return self.title
现在我要做的是:默认情况下,我想为mcq_answer,mcq_answer1,mcq_answer2,mcq_answer3设置隐藏字段。如果选中is_mcq
,那么我想在表单中显示这4个字段以获取更多答案。
我可以使用jquery的东西来显示更多字段,但是我不确定应该在哪里做。
这是admin.py文件中的代码:
from django.contrib import admin
from .models import Question
class QuestionAdmin(admin.ModelAdmin):
list_display = ('id', 'language', 'version', 'experience', 'difficulty', 'title', 'question', 'answer', 'is_mcq')
search_fields = ('language', 'experience', 'title')
list_per_page = 20
admin.site.register(Question, QuestionAdmin)
答案 0 :(得分:0)
我不确定自己要做什么,但是如果要以布尔值形式显示某些字段,可以看看jqueries toggle。这比Django问题更像是一个jquery问题。
答案 1 :(得分:0)
最后,我通过在admin.py文件上添加媒体类(js文件的链接)来解决此问题:
class QuestionAdmin(admin.ModelAdmin):
list_display = ('question', 'language', 'experience', 'difficulty', 'is_mcq')
search_fields = ('question', 'language')
list_display_links = ('question',)
list_editable = ('is_mcq',)
list_per_page = 20
class Media:
js = (
'//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js', # jquery
'js/admin.js', # project static folder
)
admin.site.register(Question, QuestionAdmin)
,然后将jQuery代码放在admin.js文件中,如下所示:
$(function() {
if (!$('#id_is_mcq').is(':checked')) {
$('.field-mcq_answer').hide();
$('.field-mcq_answer1').hide();
$('.field-mcq_answer2').hide();
$('.field-mcq_answer3').hide();
}
$('#id_is_mcq').click(function() {
if (!$(this).is(':checked')) {
$('.field-mcq_answer').hide();
$('.field-mcq_answer1').hide();
$('.field-mcq_answer2').hide();
$('.field-mcq_answer3').hide();
}else{
$('.field-mcq_answer').show();
$('.field-mcq_answer1').show();
$('.field-mcq_answer2').show();
$('.field-mcq_answer3').show();
}
});
});
希望这对像我刚开始使用Django的其他人有帮助。