Django - passing one model to another while creating new object

106
March 27, 2022, at 8:10 PM

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 ?

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

this will exclude user from form.

Here is How to set field after excluding

Rent Charter Buses Company
READ ALSO
Import could not be resolve after installing the dependency

Import could not be resolve after installing the dependency

I'm trying to install de messagebird dependency into my python project

171
With cartopy, can a local map be rotated so that north points in an arbitrary direction?

With cartopy, can a local map be rotated so that north points in an arbitrary direction?

I have this block of python code to plot a city-scale satellite map

144
python - convert curl command

python - convert curl command

I have this curl command

147
AssertionError inside of ensure_local_distutils when building a PyInstaller exe using setuptools/distutils

AssertionError inside of ensure_local_distutils when building a PyInstaller exe using setuptools/distutils

I am trying to convert some Python code into anexe with PyInstaller

226