0

In my models.py file I have a class called 'Problem', which basically stores a question, its answer and some scoring related information for that question. Here's the code for that class:

class Problem(models.Model):

 def CreatePath(instance, filename):
     return ( '/' + instance.problemLevel + '.' + (instance.primary_key) + '.html')

 # Use 'pkey' as problem ID
 problemName = models.CharField('Problem Name',max_length=50)
 problemText = RichTextField('Problem Statement',max_length=10000)
 testCases = models.TextField('Test Cases',max_length=4000)
 output = models.TextField('Test case result',max_length=4000)
 problemLevel = models.IntegerField('Problem Level')
 problemPoints = models.IntegerField('Points')
 problemLink = models.FileField(upload_to=CreatePath, blank=True)


 def save(self, *args, **kwargs):
     self.problemLink = self.problemText
     super(Problem, self).save(*args, **kwargs)

 def __unicode__(self):
     return self.problemName

After a user enters a problem through the admin page(I'm using the Ckeditor RTE for the problem text field) , I want Django to create a new html page for that specific problem. Say I enter a problem with problemLevel = 1 and assuming it is the first problem , I want 1.1.html stored into my problems(media) directory. So I tried to use a FileField object for that purpose and I slightly modified the save() module. But the file is not being created. I ran the inbuilt Django admin shell to check the contents of problemLink, and it had the same contents as problemText. Can someone tell me where I'm going wrong here? I'm a Django newbie, if that helps!

Nishad
  • 102
  • 1
  • 3
  • 9

1 Answers1

0

Why do you want to create an HTML page for it?

Usually in django you would store the data in the database - as you are doing - minus the link.

Then you have a url in you urls.py

e.g. url(r"^(?P<problemLevel>\d+)/(?P<pk>)/$", views.showProblem)

which will call showProblem() in your views.py file, which in turn will get the information and render it to HTML for the user when the user requests http://<yourserver>/1/1/.

The important part here is that all of this happens when the users requests it, not when the data is stored.

OllyTheNinja
  • 566
  • 3
  • 16
  • I wanted to avoid the overhead of querying the database and then rendering each page individually when the users of the site request them. If the problem pages are already saved as html, I just have to display that page as is. Thought this would be more efficient! – Nishad Feb 19 '14 at 02:30
  • Valid point! in that case I suggest using the `@cache_page()` decorator on your view method. See documentation [here](https://docs.djangoproject.com/en/dev/topics/cache/#the-per-view-cache) – OllyTheNinja Feb 19 '14 at 07:17