0

I am creating a wiki and need to put in values in the model called revision. This table has a foreigkey to wikipage. My problem is that I am unable to insert values in the revision model. I have tried using def form_valid(self, form) like you would when entering user, without any luck.

Models.py

class Wikipage(models.Model):
    title = models.CharField(max_length=100)
    date_created = models.DateTimeField('Created', auto_now_add=True)

    def __str__(self):
        return self.title

    class Meta:
        verbose_name_plural = "Wikipages"


class Revision(models.Model):
    wikipage = models.ForeignKey(Wikipage, null=True, on_delete=models.CASCADE, related_name='revisions')
    content = models.TextField('Content')
    author = models.ForeignKey(User, null=True, on_delete=models.SET_NULL)
    last_edit = models.DateTimeField('Last Edited', auto_now=True)
    comment = models.TextField('Comment', blank=True)

    class Meta:
        verbose_name = 'Revision'
        verbose_name_plural = 'Revisions'
        ordering = ['-last_edit']
        get_latest_by = ['last_edit']

    def __str__(self):
        return self.content

View.py

Class WikipageCreateView(CreateView):
    template_name = 'wiki/wikipageform.html'
    model = Wikipage
    fields = ['title']

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)

The template are as simple as possible with {{ form.as_p }} and all the necessary stuff.

AdrianP
  • 13
  • 4
  • Shouldn't that be `model = Revision` ? – nigel222 Jul 03 '19 at 08:19
  • @nigel222 Yep. Could do that, but then i'm not able to add the Wikipage.title value – AdrianP Jul 03 '19 at 10:52
  • `{{revision_instance.wikipage.title}}` ? You might want to clarify the question. – nigel222 Jul 03 '19 at 10:55
  • I will try to clarify: Is there something I can add in the WikipageCreateView class to have 2 additional boxes for me to put in the Revision.content and Revision.comment in the template? I am able to add Wikipage.titlewithout any problems. – AdrianP Jul 03 '19 at 16:39
  • Not really. If I understand right, you are trying to create both a new `Wikipage` object and a new `Revision` object linked to it. `CreateView` is aimed at creating a single object. I would recommend using a `FormView` with a form with fields for both objects, and a `form_valid` to instantiate both objects, link them, and save them (Wikipage object first because it wont have an id for the Revision object until it has been saved into the DB). – nigel222 Jul 03 '19 at 17:20
  • Hey again. Would it be possible to have two CreateViews? One that creates a new Wikipage object and redirects to one that creates revisions? Then you could use the last one to create new revisions for already existing wikipages. If possible: How can I redirect from one CreateView to another? – AdrianP Jul 04 '19 at 18:07

0 Answers0