用Django写一个简单的问答系统
时间: 2023-10-22 22:05:16 浏览: 31
好的,我可以为您提供一些关于用 Django 写一个简单问答系统的指导。
1. 创建一个 Django 项目和应用程序:
首先,您需要创建一个 Django 项目和应用程序。可以使用以下命令创建:
```
django-admin startproject myproject
cd myproject
python manage.py startapp myapp
```
2. 定义数据模型:
接下来,您需要定义数据模型来存储问题和答案。在 `myapp` 应用程序的 `models.py` 文件中添加以下代码:
```python
from django.db import models
class Question(models.Model):
question_text = models.CharField(max_length=200)
class Answer(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
answer_text = models.CharField(max_length=200)
```
3. 创建视图:
然后,您需要创建视图来处理用户的请求。在 `myapp` 应用程序的 `views.py` 文件中添加以下代码:
```python
from django.shortcuts import render
from django.http import HttpResponse
from .models import Question, Answer
def index(request):
question_list = Question.objects.all()
context = {'question_list': question_list}
return render(request, 'index.html', context)
def answer(request, question_id):
question = Question.objects.get(pk=question_id)
answer_list = question.answer_set.all()
context = {'question': question, 'answer_list': answer_list}
return render(request, 'answer.html', context)
```
4. 创建模板:
接下来,您需要创建模板来呈现问题和答案。在 `myapp` 应用程序的 `templates` 目录中创建以下文件:
`index.html`:
```html
{% for question in question_list %}
<a href="{% url 'myapp:answer' question.id %}">{{ question.question_text }}</a><br>
{% endfor %}
```
`answer.html`:
```html
<h1>{{ question.question_text }}</h1>
<ul>
{% for answer in answer_list %}
<li>{{ answer.answer_text }}</li>
{% endfor %}
</ul>
```
5. 配置 URL:
最后,您需要配置 URL 来将请求路由到正确的视图。在 `myapp` 应用程序的 `urls.py` 文件中添加以下代码:
```python
from django.urls import path
from . import views
app_name = 'myapp'
urlpatterns = [
path('', views.index, name='index'),
path('<int:question_id>/', views.answer, name='answer'),
]
```
现在,您的问答系统已经完成了!您可以运行 `python manage.py runserver` 命令启动 Django 开发服务器,并在浏览器中访问 `http://localhost:8000/` 来查看系统。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)