генерация формы для простого приложения обзора

Это просто дурацкий способ исправить некоторые ограничения сборки мусора в JVM.

До Java 7, если мы хотим избежать проблемы с сборкой мусора, мы всегда можем скопировать подстроку вместо сохранения ссылки на подстроку. Это был просто дополнительный вызов конструктора копирования:

String smallStr = new String(largeStr.substring(0,2));

Но теперь мы больше не можем иметь подстроку с постоянным временем. Какая катастрофа.

6
задан Nosredna 11 June 2009 в 03:13
поделиться

1 ответ

Поскольку я сам обнаружил решение, я отвечу на свой вопрос:

models.py:

CHOICES=((1,'exactly true'),(2,'mostly true'),(3,'mostly untrue'),(4,'untrue'),(5,'I don\'t know '))

class Answer(models.Model):
    question = models.ForeignKey("Question")

class ChoiceAnswer(Answer):
    answer = models.IntegerField(max_length=1, choices=CHOICES)
    def __unicode__(self):
        return u'%s: %s'%(self.question, self.answer)

class TextAnswer(Answer):
    answer= models.TextField()
    def __unicode__(self):
        return u'%s: %s'%(self.question, self.answer)

class BooleanAnswer(Answer):
    answer= models.BooleanField(choices=((True,'yes'),(False,'no')))
    def __unicode__(self):
        return u'%s: %s'%(self.question, self.answer)

class Question(models.Model):
    question = models.CharField(max_length=255)
    answer_type = models.ForeignKey(ContentType)

    def __unicode__(self):
        return u'%s'%self.question

forms.py:

class ChoiceAnswerForm(forms.ModelForm):
    class Meta:
        model = ChoiceAnswer
        exclude=("question",)
ChoiceAnswer.form = ChoiceAnswerForm

class BooleanAnswerForm(forms.ModelForm):
    class Meta:
        model = BooleanAnswer
        exclude=("question",)
BooleanAnswer.form= BooleanAnswerForm

class TextAnswerForm(forms.ModelForm):
    class Meta:
        model = TextAnswer
        exclude=("question",)
TextAnswer.form = TextAnswerForm

представление:

#needed for monkey-patching.
from survey.forms import BooleanAnswerForm, TextAnswerForm, ChoiceAnswerForm 

def index(request):
    questions = Question.objects.all() 
    if request.method == 'POST': # If the form has been submitted...
        print request.POST
        for q in questions :
            try:
                data ={ u'%s-answer'%q.id: request.POST[u'%s-answer'%q.id]}
            except:
                data = { u'%s-answer'%q.id: None}
            q.form = q.answer_type.model_class().form(prefix="%s"%q.id, data=data)    
    else:
        for q in questions :
            q.form = q.answer_type.model_class().form(prefix="%s"%q.id) 

    return render_to_response('survey.html', {
        'questions': questions,

    })  

и в шаблоне :

{% block content %}

    <div class="survey">
        <form enctype="multipart/*" action="/" method="post">

        {% for question in questions %}
            <p>{{ question.question }}</p><ul>{{ question.form.as_ul }}</ul>
        {% endfor %}

    <div><input type="submit" value="submit" /></div>
</form>
</div>

{% endblock %}

Исправления обезьяны можно было избежать с помощью какой-то регистрации. Но пока меня это устраивает.

РЕДАКТИРОВАТЬ

фильтрацию типов содержимого можно выполнить как

answer_type = models.ForeignKey(ContentType, 
              limit_choices_to = Q(name='text answer', app_label='survey')| \
                                 Q(name='boolean answer', app_label='survey')| \
                                 Q(name='choice answer', app_label='survey'))
11
ответ дан 9 December 2019 в 22:39
поделиться
Другие вопросы по тегам:

Похожие вопросы: