Reputation: 681
I'm building an online judge in which I have a Question model and an Answer model.
models.py
from django.db import models
from django.core.validators import FileExtensionValidator
from django.urls import reverse
class Question(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
solution = models.FileField(
validators=[FileExtensionValidator(allowed_extensions=['txt'])], upload_to= 'media')
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('coder:detail', kwargs={'pk': self.pk})
class Answer(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
result = models.CharField(max_length=100,default = 'answer', null = True, blank = True)
# result = models.FileField( null= True, blank=True, default = 'media/media/output.txt',
# validators=[FileExtensionValidator(allowed_extensions=['txt'])], upload_to= 'media')
def __str__(self):
return f'{self.question.title} Answer'
def get_absolute_url(self):
return reverse('coder:detail', kwargs={'pk': self.pk})
views.py
from django.shortcuts import get_object_or_404, render
from django.urls import reverse_lazy
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.views.generic import ListView, DetailView, CreateView, UpdateView, RedirectView
from django.db.models import Q
from .models import Question, Answer
class CoderListView(ListView):
model = Question
template_name = "coder/coder_list.html"
context_object_name = 'question'
class CoderDetailView(DetailView):
model = Question
template_name = "coder/coder_detail.html"
class CoderCreateView(CreateView):
model = Answer
fields = ['result']
context_object_name = 'answer'
success_url = reverse_lazy('coder:list')
template_name = "coder/coder_form.html"
def form_valid(self, form):
return super().form_valid(form)
What exactly am I doing wrong here?
I was trying out FileField earlier but when I kept getting an error, I tried CharField after flushing the database to debug further but I kept getting this error:
And yes, I did try out setting null, blank, and default values appropriately but still no luck. Maybe something to do with a signals.py
file? Or maybe I'm implementing the Foreign key wrong, whatever it is that I'm doing wrong I'm unable to point out at the moment. Help with that would be appreciated.
This page is using CoderCreateView.
Upvotes: 0
Views: 158
Reputation: 2383
I believe this is what caused the problem:
class CoderCreateView(CreateView):
model = Answer
fields = ['result']
context_object_name = 'answer'
For the answer model, you forget to pass in the primary key/object (whichever way you prefer) of the question that the answer is linked to, as in this line in your models.py
:
question = models.ForeignKey(Question, on_delete=models.CASCADE)
Upvotes: 1