Home > Software design >  Django - passing one model to another while creating new object
Django - passing one model to another while creating new object

Time:02-08

My site has multiple tests with multiple questions each. I'd like to make question creation form which will have preset test object depended on url. it's better explained in comment in views.py

That's what I have already done;

models

class Test(models.Model):
    name = models.CharField(max_length=200)
    #questions = models.ManyToManyField(Question)
    author = models.ForeignKey(User, on_delete=models.CASCADE, default=None, null=True, blank=True)
    date_posted = models.DateTimeField(auto_now_add = True)

    def get_questions(self):
        return self.question_set.all()

    def __str__(self):
        return self.name

class Question(models.Model):

    text = models.CharField(max_length=200, null=True)
    test = models.ForeignKey(Test, on_delete=models.CASCADE)
    created = models.DateTimeField(auto_now_add = True)

    def __str__(self):
         return self.text

urls

urlpatterns = [
    path('', views.home, name='home'),
    path('test/<str:pk>/', views.test),

    path('test/<str:pk>/question-create/', views.QuestionCreateView, name='question-create'),

]

forms

from django import forms
from django.forms import ModelForm
from .models import Question, 


class QuestionCreationForm(ModelForm):
    class Meta:
        model = Question
        fields = '__all__'  /// all except test which is set by pk in url 

views

def QuestionCreateView(request, pk):

    form = QuestionCreationForm()
    if request.method == 'POST':
        test = Test.objects.get(id=pk)   /// I would like to pass it to models to disallow user to choose to which test will question belong, i mean test should pe preset by <pk> in link
        
        form = QuestionCreationForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('home')

    context = {'form':form}
    return render(request, 'exam/question_form.html', context)

what should I add/change to disallow user to choose test while creating new question ?

CodePudding user response:

class QuestionCreationForm(ModelForm):
    class Meta:
        model = Question
        exclude = ('user',)

this will exclude user from form.

Here is How to set field after excluding

  •  Tags:  
  • Related