使用DJango实现动漫信息管理实现动漫信息包括标题为charfield类型,图片为ImageField,时间为datefiled 要求实现增删改功能要html代码和models代码以及url和form
时间: 2024-03-18 15:40:57 浏览: 123
以下是实现动漫信息管理的示例代码:
## models.py
```python
from django.db import models
class Anime(models.Model):
title = models.CharField(max_length=100)
image = models.ImageField(upload_to='images/')
date = models.DateField()
def __str__(self):
return self.title
```
## forms.py
```python
from django import forms
from .models import Anime
class AnimeForm(forms.ModelForm):
class Meta:
model = Anime
fields = ['title', 'image', 'date']
```
## views.py
```python
from django.shortcuts import render, redirect
from .models import Anime
from .forms import AnimeForm
def anime_list(request):
animes = Anime.objects.all()
return render(request, 'anime_list.html', {'animes': animes})
def anime_add(request):
if request.method == 'POST':
form = AnimeForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('anime_list')
else:
form = AnimeForm()
return render(request, 'anime_form.html', {'form': form})
def anime_edit(request, pk):
anime = Anime.objects.get(pk=pk)
if request.method == 'POST':
form = AnimeForm(request.POST, request.FILES, instance=anime)
if form.is_valid():
form.save()
return redirect('anime_list')
else:
form = AnimeForm(instance=anime)
return render(request, 'anime_form.html', {'form': form})
def anime_delete(request, pk):
anime = Anime.objects.get(pk=pk)
anime.delete()
return redirect('anime_list')
```
## urls.py
```python
from django.urls import path
from . import views
urlpatterns = [
path('', views.anime_list, name='anime_list'),
path('add/', views.anime_add, name='anime_add'),
path('edit/<int:pk>/', views.anime_edit, name='anime_edit'),
path('delete/<int:pk>/', views.anime_delete, name='anime_delete'),
]
```
## anime_list.html
```html
{% extends 'base.html' %}
{% block content %}
<h1>Anime List</h1>
<a href="{% url 'anime_add' %}">Add Anime</a>
<table>
<thead>
<tr>
<th>Title</th>
<th>Image</th>
<th>Date</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{% for anime in animes %}
<tr>
<td>{{ anime.title }}</td>
<td><img src="{{ anime.image.url }}" width="100"></td>
<td>{{ anime.date }}</td>
<td>
<a href="{% url 'anime_edit' anime.pk %}">Edit</a>
<a href="{% url 'anime_delete' anime.pk %}">Delete</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock %}
```
## anime_form.html
```html
{% extends 'base.html' %}
{% block content %}
<h1>{% if form.instance.pk %}Edit{% else %}Add{% endif %} Anime</h1>
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Save</button>
</form>
{% endblock %}
```
注意:上述代码只是示例代码,需要根据具体情况进行适当修改。另外,还需要在settings.py文件中配置MEDIA_ROOT和MEDIA_URL,以便正确处理上传的图片。
阅读全文