在Django中,可以通过使用外键字段来将固定选择链接到新创建的问题。外键字段是一种关系字段,用于建立模型之间的关联。
以下是在Django中将固定选择链接到新创建的问题的步骤:
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)
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')
<!-- 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>
from django.urls import path
from . import views
urlpatterns = [
path('create/', views.create_question, name='create_question'),
]
这样,当用户访问/create/
路径时,将显示一个表单,用户可以输入问题和固定选择的选项。提交表单后,将创建一个新的问题和相应的固定选择,并将用户重定向到问题详情页面。
这是一个简单的示例,你可以根据实际需求进行修改和扩展。关于Django的更多信息和详细文档,请参考腾讯云的Django产品介绍。
领取专属 10元无门槛券
手把手带您无忧上云