首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何在django中将固定选择链接到新创建的问题

在Django中,可以通过使用外键字段来将固定选择链接到新创建的问题。外键字段是一种关系字段,用于建立模型之间的关联。

以下是在Django中将固定选择链接到新创建的问题的步骤:

  1. 创建模型:首先,在Django的模型文件中定义两个模型,一个是问题模型,另一个是固定选择模型。问题模型用于存储问题的信息,固定选择模型用于存储固定选择的选项。
代码语言:txt
复制
from django.db import models

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)
  1. 创建视图:接下来,在Django的视图文件中创建视图函数,用于处理用户提交的问题和固定选择。
代码语言:txt
复制
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponseRedirect
from django.urls import reverse

from .models import Question, Choice

def create_question(request):
    if request.method == 'POST':
        question_text = request.POST['question_text']
        pub_date = request.POST['pub_date']
        question = Question(question_text=question_text, pub_date=pub_date)
        question.save()
        
        choice_texts = request.POST.getlist('choice_text')
        for choice_text in choice_texts:
            choice = Choice(question=question, choice_text=choice_text)
            choice.save()
        
        return HttpResponseRedirect(reverse('question_detail', args=(question.id,)))
    
    return render(request, 'create_question.html')
  1. 创建模板:然后,在Django的模板文件中创建一个表单,用于用户输入问题和固定选择的选项。
代码语言:txt
复制
<!-- create_question.html -->
<form method="post" action="{% url 'create_question' %}">
  {% csrf_token %}
  <label for="question_text">Question:</label>
  <input type="text" name="question_text" id="question_text">
  <br>
  <label for="pub_date">Publication Date:</label>
  <input type="datetime-local" name="pub_date" id="pub_date">
  <br>
  <label for="choice_text">Choices:</label>
  <input type="text" name="choice_text" id="choice_text">
  <br>
  <input type="submit" value="Create">
</form>
  1. 创建URL映射:最后,在Django的URL配置文件中创建URL映射,将视图函数和模板进行关联。
代码语言:txt
复制
from django.urls import path

from . import views

urlpatterns = [
    path('create/', views.create_question, name='create_question'),
]

这样,当用户访问/create/路径时,将显示一个表单,用户可以输入问题和固定选择的选项。提交表单后,将创建一个新的问题和相应的固定选择,并将用户重定向到问题详情页面。

这是一个简单的示例,你可以根据实际需求进行修改和扩展。关于Django的更多信息和详细文档,请参考腾讯云的Django产品介绍

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券