0

I'm still very new to programming and I'm worried that I'm barking up the wrong tree. I'm trying to write a multiple choice quiz app. I have 5000 different words and their definitions. I've made two dictionaries. One with the word definitions and one with 4 choice - 1 of which is the correct answer.

I've already got written the model classes. I've also have generated a txt file that I can copy into the django shell. This links a definition to the 4 possible answers, and assigns True to the correct one. But since there are many words, I want to automate the entry into the django shell. Can I do that?

First I tried writing a batch file but that doesn't work once the shell is opened.

I've also tried reading this:

https://docs.djangoproject.com/en/1.9/howto/custom-management-commands/

I produced a complete monstrosity of code that I knew wouldn't work! I don't quite understand what's going on in the above link. Or even if it suits my purposes.

Anyway, here's the text I generated. I can copy this, line by line, into the django shell. It will do what I want (or at least what I think I want - I may be going about this the wrong way for all I know!) But obviously I want to do it with one click rather than copy and paste 30000 lines of text.

from quiz.models import Question, Class
    q1=Question(question_text="used to refer to somebody/something that has already been mentioned or is easily understood,")
    q1.save()
    q1.choice_set.create(choice_text='the', rorwrong=True)
    q1.choice_set.create(choice_text='be', rorwrong=False)
    q1.choice_set.create(choice_text='of', rorwrong=False)
    q1.choice_set.create(choice_text='a', rorwrong=False)
    ....
    q1849=Question(question_text="to be frightened of somebody/something or frightened of doing something,")
    q1849.save()
    q1849.choice_set.create(choice_text='detail', rorwrong=False)
    q1849.choice_set.create(choice_text='fear', rorwrong=True)
    q1849.choice_set.create(choice_text='beautiful', rorwrong=False)
    q1849.choice_set.create(choice_text='institution', rorwrong=False)

Here are my model classes:

from django.db import models

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    def __str__(self):
        return(self.question_text)


class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    rorwrong = models.BooleanField(default=False)
    def __str__(self):
        return(self.choice_text)

1 Answers1

1

A custom management command is indeed what you need to perform tasks like this. I would put your data into a CSV file and them import it with something like this:

# myapp/management/commands/import_questions.py
import csv

from django.core.management.base import BaseCommand
from myapp.models import Question

class Command(BaseCommand):

    def add_arguments(self, parser):
        parser.add_argument('csvfile', nargs='+', type=str)

    def handle(self, *args, **options):
        for f in options['csvfile']:
            with open(f) as csvfile:
                reader = csv.reader(csvfile)
                for row in reader:
                    # Say the CSV rows are as follows: 
                    # <Question title>, <Answer1Text>, <Answer1Correct> ... etc 
                    q = Question(question_text=row[0])
                    q.save()
                    q.choice_set.create(choice_text=row[1], rorwrong=bool(row[2]))
                    q.choice_set.create(choice_text=row[3], rorwrong=bool(row[4])) 
                    # Etc for the rest of them

You would then execute this command with:

./manage.py import_questions --csvfile data.csv
solarissmoke
  • 30,039
  • 14
  • 71
  • 73
  • I've tried doing what you've said but I get the error message: The system cannot find the file specified. I've tried putting it in the 'myapp' directory and the 'command' directory – Bill Gilroy Aug 03 '16 at 05:33
  • The file needs to be in the same directory as `manage.py`. Alternatively supply an absolute path to the file in the argument. – solarissmoke Aug 03 '16 at 05:47
  • Thanks a lot for your help - I finally got the command to execute. Bad news is that nothing has appeared on the admin site. Any clues? – Bill Gilroy Aug 03 '16 at 07:21
  • No idea... if you didn't get errors then presumably the objects were saved in the database. – solarissmoke Aug 03 '16 at 08:11
  • Nothing has changed in the database and I had no errors. I added self.stdout.write(self.style.SUCCESS(row[])) at the end of the loop and it generated the following (and so on) as I would have wanted: q1=Question(question_text="blahblah,") q1.save() q1.choice_set.create(choice_text='the', rorwrong=True) q1.choice_set.create(choice_text='be', rorwrong=False) q1.choice_set.create(choice_text='of', rorwrong=False) q1.choice_set.create(choice_text='a', rorwrong=False) If I copy and paste these into shell, it will work. Is there anything I'm missing? – Bill Gilroy Aug 03 '16 at 08:32
  • Wait no, that is not what I meant at all.... the CSV file should not contain Python code, just the raw data that you want to import - see the comment in the code sample I posted. – solarissmoke Aug 03 '16 at 09:10