Django не добавляет вопрос класса с формами - PullRequest
0 голосов
/ 01 августа 2020

Я создал приложение под названием /f/ask/ и на этой странице я добавляю класс Question в форму, но я не знаю, почему он не добавляет этот класс в мою базу данных. Вот мои файлы.

спрос. html

    <!DOCTYPE html>
{% load static %}
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="{% static 'f/ask/ask.css' %}">
        <title>BareTalk</title>
    </head>
    <body>
        <div id="wrapper"> 
            <form method="post">
                {% csrf_token %}
                {{ form }}

                <!-- TODO: input submit Reg() function javascript -->
                <input name="final" id="final" type="submit" value="Ask">
            </form>
        </div>
    </body>
    <script src="{% static 'f/ask/ask.js' %}"></script>
</html>

views.py

from django.views.generic.edit import CreateView
from django.shortcuts import render
from .forms import QuestionForm
from .models import *

def QuestionView(request):
    ''' List of Questions '''
    questions = Question.objects.all()
    return render(request, 'f/index.html', {'question_list': questions})

def QuestionCurrent(request, pk):
    ''' Current Question '''
    question = Question.objects.get(id=pk)
    return render(request, 'f/current.html', {'question': question})

def ask(request):
    form = QuestionForm()
    if request.method == 'POST':
        form = QuestionForm(request.POST)
        if form.is_valid():
            form.save(commit=False)

    content = {'form': form}

    return render(request, 'f/ask.html', content)

urls.py

from django.urls import path, register_converter
from . import views, converter

register_converter(converter.HexConverter, 'hex')

urlpatterns = [
    path('', views.QuestionView, 'f'),
    path('ask/', views.ask, name='ask'),
    path('<hex:pk>/', views.QuestionCurrent, name='question_current'),
]

forms.py

from django.forms import ModelForm
from .models import *

class QuestionForm(ModelForm):
    class Meta:
        model = Question
        fields = '__all__'

models.py

from django.db import models

# ---------- Question ----------

class Question(models.Model):
    ''' Questions '''

    author     = models.CharField('Author', max_length=45)
    title      = models.CharField('Title', max_length=300)
    body       = models.TextField('Body')
    date       = models.DateTimeField(auto_now_add=True, db_index=True)

    def __str__(self):
        return self.title

    class Meta:
        verbose_name_plural = 'Questions'
        verbose_name        = 'Question'

# ---------- Answer ----------

class Answer(models.Model):
    ''' Answers '''

    author   = models.CharField('Author', max_length=45)
    title    = models.CharField('Title', max_length=300)
    body     = models.TextField('Body')
    date     = models.DateTimeField(auto_now_add=True, db_index=True)
    question   = models.ForeignKey(Question, on_delete=models.CASCADE)
    rating   = models.IntegerField()
    isAnswer = models.BooleanField()

    def __str__(self):
        return self.title
    
    class Meta:
        verbose_name_plural = 'Answers'
        verbose_name        = 'Answer'

1 Ответ

0 голосов
/ 01 августа 2020

Я считаю, что ваша проблема связана с этой строкой:

if form.is_valid():
    form.save(commit=False)

Если у вас нет дополнительных данных для добавления к вашему объекту, вы должны удалить атрибут commit=False. commit=True включен по умолчанию.

Документация

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...