Форма Django недействительна и не отправляется? [закрыто]

У меня есть четыре основные части: Форма BaseJournal, Форма JournalTemplate, модель Journal и мое представление, которое ее обрабатывает.

Вот модель журнала:

class Journal(models.Model):
MOOD_CHOICES = [
    ('happy', 'happy.png'),
    ('angry', 'angry.png'),
    ('neutral', 'neutral.png'),
    ('sad', 'sad.png'),
]

user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
date = models.DateField(auto_now_add=True, editable=False)
title = models.CharField(blank=False, max_length=50, default="default title")
mood = models.CharField(max_length=20, choices=MOOD_CHOICES, default='neutral')
custom_fields = JSONField(default=dict)
field_order = JSONField(default=list)

@property
def attached_files(self):
    return AttachedFile.objects.filter(journal=self)

Вот форма BaseJournal:

class BaseJournalForm(forms.ModelForm):
def __init__(self, user=None, **kwargs):
    super().__init__(**kwargs)
    self.fields['mood'].label = ''

files = MultipleFileField(required=False)

class Meta:
    model = Journal
    fields = ['title', 'files', 'mood']
    widgets = {
        "mood": forms.HiddenInput(),
        "files": MultipleFileInput(),
    }

Вот моя форма шаблона журнала:

class JournalEntryForm(BaseJournalForm):
template = forms.ModelChoiceField(
    queryset=JournalTemplate.objects.all(),
    empty_label='No Template',  # Set the placeholder text
    required=False,
    widget=forms.Select(attrs={'class': 'form-control'})
)
num_questions = forms.IntegerField(label='Number of Questions', required=False, widget=forms.NumberInput(attrs={'class': 'form-control'}), min_value=0)
num_feelings = forms.IntegerField(label='Number of Feelings', required=False, widget=forms.NumberInput(attrs={'class': 'form-control'}), min_value=0)
num_subheadings = forms.IntegerField(label='Number of Subheadings', required=False, widget=forms.NumberInput(attrs={'class': 'form-control'}), min_value=0)
num_events = forms.IntegerField(label='Number of Events', required=False, widget=forms.NumberInput(attrs={'class': 'form-control'}), min_value=0)
template_name = forms.CharField(label='Template Name', required=False, widget=forms.TextInput(attrs={'class': 'form-control'}))

class Meta:
    model = Journal
    fields = BaseJournalForm.Meta.fields + ['template', 'num_questions', 'num_feelings', 'num_subheadings', 'num_events', 'template_name']

Вот мое представление, которое обрабатывает форму:

def create_journal_entry(request):
templates = JournalTemplate.objects.all()

if request.method == 'POST':
    form = JournalEntryForm(request.POST)
    if form.is_valid():
        template = form.cleaned_data.get('template')
        template_name = form.cleaned_data.get('template_name')
        num_questions = form.cleaned_data.get('num_questions')
        num_feelings = form.cleaned_data.get('num_feelings')
        num_subheadings = form.cleaned_data.get('num_subheadings')
        num_events = form.cleaned_data.get('num_events')
   
        if not template and not template_name:
            form.add_error(None, "Please provide a template name.")
            return render(request, 'create_journal_entry.html', {'form': form, 'template_select_enabled': False, 'templates': templates})
        elif not template:
            # Create and save the custom template
            template = JournalTemplate.objects.create(
                template_name=template_name,
                num_questions=num_questions,
                num_feelings=num_feelings,
                num_subheadings=num_subheadings,
                num_events=num_events
            )

        combined_template = create_combined_template(num_questions, num_feelings, num_subheadings, num_events)
        questions = list(range(1, num_questions + 1))
        events = list(range(1, num_events + 1))
        subheadings = list(range(1, num_subheadings + 1))
        feelings = list(range(1, num_feelings + 1))
        return render(request, 'create_journal_entry.html', {'combined_template': combined_template, 'questions': questions, 'events': events, 'subheadings': subheadings, 'feelings': feelings, 'template_name': template.template_name, 'form': form})
    else:
        # Form is invalid, render the form with errors
        print("form is invalid")
        return render(request, 'create_journal_entry.html', {'form': form, 'template_select_enabled': False, 'templates': templates})
else:
    form = JournalEntryForm()
    form.fields['template'].queryset = templates
    return render(request, 'create_journal_entry.html', {'form': form, 'template_select_enabled': False, 'templates': templates})

У меня есть четыре основные части: Форма BaseJournal, Форма JournalTemplate, модель Journal и представление amy, которое ее обрабатывает.

Вот модель журнала:

class Journal(models.Model):
MOOD_CHOICES = [
    ('happy', 'happy.png'),
    ('angry', 'angry.png'),
    ('neutral', 'neutral.png'),
    ('sad', 'sad.png'),
]

user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
date = models.DateField(auto_now_add=True, editable=False)
title = models.CharField(blank=False, max_length=50, default="default title")
mood = models.CharField(max_length=20, choices=MOOD_CHOICES, default='neutral')
custom_fields = JSONField(default=dict)
field_order = JSONField(default=list)

@property
def attached_files(self):
    return AttachedFile.objects.filter(journal=self)

Вот форма BaseJournal:

class BaseJournalForm(forms.ModelForm):
def __init__(self, user=None, **kwargs):
    super().__init__(**kwargs)
    self.fields['mood'].label = ''

files = MultipleFileField(required=False)

class Meta:
    model = Journal
    fields = ['title', 'files', 'mood']
    widgets = {
        "mood": forms.HiddenInput(),
        "files": MultipleFileInput(),
    }

Вот моя форма шаблона журнала:

class JournalEntryForm(BaseJournalForm):
template = forms.ModelChoiceField(
    queryset=JournalTemplate.objects.all(),
    empty_label='No Template',  # Set the placeholder text
    required=False,
    widget=forms.Select(attrs={'class': 'form-control'})
)
num_questions = forms.IntegerField(label='Number of Questions', required=False, widget=forms.NumberInput(attrs={'class': 'form-control'}), min_value=0)
num_feelings = forms.IntegerField(label='Number of Feelings', required=False, widget=forms.NumberInput(attrs={'class': 'form-control'}), min_value=0)
num_subheadings = forms.IntegerField(label='Number of Subheadings', required=False, widget=forms.NumberInput(attrs={'class': 'form-control'}), min_value=0)
num_events = forms.IntegerField(label='Number of Events', required=False, widget=forms.NumberInput(attrs={'class': 'form-control'}), min_value=0)
template_name = forms.CharField(label='Template Name', required=False, widget=forms.TextInput(attrs={'class': 'form-control'}))

class Meta:
    model = Journal
    fields = BaseJournalForm.Meta.fields + ['template', 'num_questions', 'num_feelings', 'num_subheadings', 'num_events', 'template_name']

Вот мое представление, которое обрабатывает форму:

def create_journal_entry(request):
templates = JournalTemplate.objects.all()

if request.method == 'POST':
    form = JournalEntryForm(request.POST)
    if form.is_valid():
        template = form.cleaned_data.get('template')
        template_name = form.cleaned_data.get('template_name')
        num_questions = form.cleaned_data.get('num_questions')
        num_feelings = form.cleaned_data.get('num_feelings')
        num_subheadings = form.cleaned_data.get('num_subheadings')
        num_events = form.cleaned_data.get('num_events')
   
        if not template and not template_name:
            form.add_error(None, "Please provide a template name.")
            return render(request, 'create_journal_entry.html', {'form': form, 'template_select_enabled': False, 'templates': templates})
        elif not template:
            # Create and save the custom template
            template = JournalTemplate.objects.create(
                template_name=template_name,
                num_questions=num_questions,
                num_feelings=num_feelings,
                num_subheadings=num_subheadings,
                num_events=num_events
            )

        combined_template = create_combined_template(num_questions, num_feelings, num_subheadings, num_events)
        questions = list(range(1, num_questions + 1))
        events = list(range(1, num_events + 1))
        subheadings = list(range(1, num_subheadings + 1))
        feelings = list(range(1, num_feelings + 1))
        return render(request, 'create_journal_entry.html', {'combined_template': combined_template, 'questions': questions, 'events': events, 'subheadings': subheadings, 'feelings': feelings, 'template_name': template.template_name, 'form': form})
    else:
        # Form is invalid, render the form with errors
        print("form is invalid")
        return render(request, 'create_journal_entry.html', {'form': form, 'template_select_enabled': False, 'templates': templates})
else:
    form = JournalEntryForm()
    form.fields['template'].queryset = templates
    return render(request, 'create_journal_entry.html', {'form': form, 'template_select_enabled': False, 'templates': templates})

Дайте мне знать, если нужна дополнительная информация или код. Спасибо за любую помощь

Повторно отправляет форму недействительной, но я не знаю, как или почему она недействительна.

Вернуться на верх