写一个完整的django实战网页代码
时间: 2024-02-28 13:56:26 浏览: 111
以下是一个简单的Django实战网页示例代码,它包括一个基本的登录/注销功能和一个简单的待办事项列表:
在`models.py`中定义模型:
```python
from django.db import models
from django.contrib.auth.models import User
class Task(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
description = models.CharField(max_length=100)
completed = models.BooleanField(default=False)
def __str__(self):
return self.description
```
在`forms.py`中定义表单类:
```python
from django import forms
from .models import Task
class TaskForm(forms.ModelForm):
class Meta:
model = Task
fields = ['description']
```
在`views.py`中定义视图函数:
```python
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login, logout
from .models import Task
from .forms import TaskForm
def user_login(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('task_list')
else:
return render(request, 'login.html', {'error_message': 'Invalid login credentials.'})
else:
return render(request, 'login.html')
@login_required
def user_logout(request):
logout(request)
return redirect('user_login')
@login_required
def task_list(request):
tasks = Task.objects.filter(user=request.user)
return render(request, 'task_list.html', {'tasks': tasks})
@login_required
def add_task(request):
if request.method == 'POST':
form = TaskForm(request.POST)
if form.is_valid():
task = form.save(commit=False)
task.user = request.user
task.save()
return redirect('task_list')
else:
form = TaskForm()
return render(request, 'add_task.html', {'form': form})
```
在`urls.py`中定义URL路由:
```python
from django.urls import path
from .views import user_login, user_logout, task_list, add_task
urlpatterns = [
path('login/', user_login, name='user_login'),
path('logout/', user_logout, name='user_logout'),
path('tasks/', task_list, name='task_list'),
path('tasks/add/', add_task, name='add_task'),
]
```
最后,在模板中使用上述视图函数所返回的数据:
`base.html`:
```html
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}{% endblock %}</title>
</head>
<body>
{% if user.is_authenticated %}
<p>Logged in as {{ user.username }}. <a href="{% url 'user_logout' %}">Logout</a></p>
{% else %}
<p><a href="{% url 'user_login' %}">Login</a></p>
{% endif %}
{% block content %}
{% endblock %}
</body>
</html>
```
`login.html`:
```html
{% extends 'base.html' %}
{% block title %}Login{% endblock %}
{% block content %}
<h1>Login</h1>
{% if error_message %}
<p>{{ error_message }}</p>
{% endif %}
<form method="post">
{% csrf_token %}
<label for="username">Username:</label>
<input type="text" name="username" id="username"><br>
<label for="password">Password:</label>
<input type="password" name="password" id="password"><br>
<button type="submit">Login</button>
</form>
{% endblock %}
```
`task_list.html`:
```html
{% extends 'base.html' %}
{% block title %}Task List{% endblock %}
{% block content %}
<h1>Task List</h1>
<ul>
{% for task in tasks %}
<li>{{ task.description }}{% if task.completed %} (Completed){% endif %}</li>
{% endfor %}
</ul>
<a href="{% url 'add_task' %}">Add a Task</a>
{% endblock %}
```
`add_task.html`:
```html
{% extends 'base.html' %}
{% block title %}Add a Task{% endblock %}
{% block content %}
<h1>Add a Task</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Save</button>
</form>
{% endblock %}
```
注意,这个示例程序并没有包括任何数据库配置。你需要在`settings.py`文件中配置数据库连接,以便在使用模型时能够连接到数据库。此外,你还需要在`urls.py`文件中包含该应用程序的URL路由,以便Django能够找到和调用视图函数。
阅读全文