Обработка MongoEngine DynamicEmbeddedDocument в Flask-Admin
У меня есть проблема, для которой я не могу найти простое решение, используя Flask-Admin с MongoEngine.
У меня есть класс Document с именем ExerciseResourceContent
. Он имеет атрибут "вопросы", который является ListField
EmbeddedDocument
, называемым ExerciseQuestion
:
class ExerciseResourceContent(ResourceContent):
"""An exercise with a list of questions."""
## Embedded list of questions
questions = db.ListField(db.EmbeddedDocumentField(ExerciseQuestion))
Документ ExerciseQuestion
на самом деле является DynamicEmbeddedDocument
:
class ExerciseQuestion(db.DynamicEmbeddedDocument):
"""
Generic collection, every question type will inherit from this.
Subclasses should override method "without_correct_answer" in order to define the version sent to clients.
Subclasses of questions depending on presentation parameters should also override method "with_computed_correct_answer".
"""
_id = db.ObjectIdField(default=ObjectId)
## Question text
question_text = db.StringField(required=True)
## Correct answer (field type depends on question type)
correct_answer = db.DynamicField()
Он может быть подклассифицирован в двух классах (еще впереди): MultipleAnswerMCQExerciseQuestion и UniqueAnswerMCQExerciseQuestion:
class MultipleAnswerMCQExerciseQuestion(ExerciseQuestion):
"""Multiple choice question with several possible answers."""
## Propositions
propositions = db.ListField(db.EmbeddedDocumentField(MultipleAnswerMCQExerciseQuestionProposition))
## Correct answer
correct_answer = db.ListField(db.ObjectIdField())
class UniqueAnswerMCQExerciseQuestion(ExerciseQuestion):
"""Multiple choice question with one possible answer only."""
## Propositions
propositions = db.ListField(db.EmbeddedDocumentField(UniqueAnswerMCQExerciseQuestionProposition))
## Correct answer
correct_answer = db.ObjectIdField()
Когда я использую Flask-Admin для создания или редактирования ExerciseResourceContent
, он отображает список "Вопрос", из которого я могу редактировать атрибут "Question_text", но я не вижу атрибута "Correct_Answer", Атрибут "Предложения", как и я.
Я боролся с документом Flask-Admin, но, похоже, проблема с динамическим материалом (полями или документами), и в документах ничего нет.
Спасибо за помощь
Ответы
Ответ 1
Мне кажется, что вам нужно настроить админ-просмотр для своих моделей. Это задача, которую вы должны выполнить для своих моделей, если они не отображаются правильно "из коробки".
В большинстве случаев вам не нужно полностью переписывать представления. В большинстве случаев этого будет достаточно, чтобы настроить встроенные представления.
У меня нет опыта разработки для фляжки, но в основном вам придется подклассы ModelView
. и зарегистрировать подкласс для администратора
#Customized admin views
class ExerciseQuestionView(ModelView):
#
# add customisation code here
#
class MultipleAnswerMCQExerciseQuestionView(ModelView):
#
# add customisation code here
#
class UniqueAnswerMCQExerciseQuestionView(ModelView):
#
# add customisation code here
#
if __name__ == '__main__':
# Create admin
admin = admin.Admin(app, 'Example: MongoEngine')
# Add admin views
admin.add_view(ExerciseQuestionView(ExerciseQuestion))
admin.add_view(MultipleAnswerMCQExerciseQuestionView(MultipleAnswerMCQExerciseQuestion))
admin.add_view(UniqueAnswerMCQExerciseQuestionView(UniqueAnswerMCQExerciseQuestion))
#...
В любом случае, я думаю, вы должны пройти документацию... или вы можете в конечном итоге слишком долго ждать здесь...
http://flask-admin.readthedocs.io/en/latest/api/mod_contrib_mongoengine/
Ответ 2
import time
sentence = "ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR COUNTRY"
s = sentence.split()
another = [0]
time.sleep(0.5)
print(sentence)
for count, i in enumerate(s):
if s.count(i) < 2:
another.append(max(another) + 1)
else:
another.append(s.index(i) +1)
another.remove(0)
time.sleep(0.5)
print(another)
file = open("N:\(Filedirectory)","w")
file.write(another)
file.write(s)