Django:使用TemplateView在Django表单中添加编辑和删除功能的问题

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django:使用TemplateView在Django表单中添加编辑和删除功能的问题相关的知识,希望对你有一定的参考价值。

我正在通过构建一个名为TravelBuddies的应用程序来学习Django。它将允许旅行者计划行程并保留相关的旅行项目(例如预订,机票,护照副本,保险信息等),以及为日常活动创建提醒。该应用程序还将能够向旅行者更新本地信息,例如天气或每日新闻。旅行者还可以与某人共享旅行信息,或让某人与他们合作来计划旅行。

我创建了一个表格,使用户能够添加他们的行程信息,例如行程名称,计划者姓名,共同计划者,日期等。但是,我找不到允许他们编辑和删除表格的正确方法。我看过一些视频。但是他们没有像我一样使用TemplateView。所以,我有点困惑。

这是我的代码在addtrip文件夹下的forms.py文件中:

from django import forms
from django.contrib.auth.models import User
from django.forms import ModelForm
from trips.models import Trip

class TripForm(ModelForm):
    class Meta:
        model = Trip
        fields = ['trip_name', 'date', 'planner_name', 'add_coplanner', 'trip_description']

class UserForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput)

    class Meta:
        model = User
        fields = ['username', 'email', 'password']

这是我的代码在addtrip文件夹下的views.py文件中:

from django.contrib.auth import mixins, authenticate, login
from django.shortcuts import render, redirect
from django.views.generic import TemplateView
from .forms import TripForm, UserForm
from trips.models import Trip
from django.http import HttpResponseRedirect
from django.urls import reverse

# Create your views here.


class AddTripFormView(mixins.LoginRequiredMixin, TemplateView):
    login_url = 'login/'
    template_name = 'addtrip/addtripform.html'

    def get(self, request):
        form = TripForm()
        trips = Trip.objects.all()
        args = {'form': form, 'trips': trips}
        return render(request, self.template_name, args)

    def post(self, request):
        form = TripForm(request.POST)
        if form.is_valid():
            form.save()
            trip_name = form.cleaned_data['trip_name']
            date = form.cleaned_data['date']
            planner_name = form.cleaned_data['planner_name']
            trip_description = form.cleaned_data['trip_description']
            args = {'form': form, 'trip name': trip_name, 'date': date, 'planner name': planner_name, 'trip description': trip_description}
            return HttpResponseRedirect(reverse('trips:triplist'))

class AddUserFormView(TemplateView):
    template_name = 'addtrip/registrationform.html'

    # Display blank form
    def get(self, request):
        form = UserForm()
        args = {'form': form}
        return render(request, self.template_name, args)

    # Process form data
    def post(self, request):
        form = UserForm(request.POST)
        if form.is_valid():
            user = form.save(commit=False)
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user.set_password(password)
            user.save()
            # return user object if credentials are correct
            user = authenticate(username=username, password=password)
            if user is not None:
                if user.is_active:
                    login(request, user)
                    return redirect('addtrip:login')

        return render(request, self.template_name, {'form': form})

这是我的代码在addtrip文件夹下的urls.py文件中:

from . import views
from django.urls import path
from django.contrib.auth import views as auth_views

app_name = 'addtrip'

urlpatterns = [
    path('addtrip/', views.AddTripFormView.as_view(), name='addtrip'),
    path('register/', views.AddUserFormView.as_view(), name='register'),
    # login
    path('addtrip/login/', auth_views.LoginView.as_view(template_name='addtrip/login.html'), name='login'),
    # logout
    path('logout/', auth_views.LogoutView.as_view(), name='logout'),
]

这是我在templates文件夹内的addtripform.html文件中的代码:

{% extends 'base.html' %}
{% load static %}

{% block title %} Add Trip {% endblock %}

{% block content %}

<div class="container">
    <h2>Add New Trip</h2>
    <form method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Submit</button>
    </form>
{% endblock %}

这是我的代码在trips文件夹内的models.py中:

from django.contrib.auth.models import User
from django.db import models

class Trip(models.Model):
    trip_name = models.CharField(max_length=100)
    date = models.DateField()
    planner_name = models.CharField(max_length=100)
    add_coplanner = models.ManyToManyField(User)
    trip_description = models.CharField(max_length=1000, default='null')
    slug = models.SlugField(max_length=150, default='null')

    def __str__(self):
        return self.trip_name

    def save(self, *args, **kwargs):
        self.slug = slugify(self.trip_name)
        super().save(*args, **kwargs)


class Activity(models.Model):
    trip = models.ForeignKey(Trip, on_delete=models.CASCADE)
    activity_name = models.CharField(max_length=100)
    date = models.DateField()
    time = models.TimeField()
    location = models.CharField(max_length=100)
    activity_description = models.CharField(max_length=1000, default='null')
    item_type = models.CharField(max_length=100)
    item_number = models.CharField(max_length=100)
    add_cotraveller = models.ManyToManyField(User)
    slug = models.SlugField(max_length=150, default='null')

    def __str__(self):
        return self.activity_name

    def save(self):
        super(Activity, self).save()
        self.slug = '%i-%s' % (
            self.id, slugify(self.trip.trip_name)
        )
        super(Activity, self).save()

这是我的代码在trips文件夹内的urls.py中:

from . import views
from django.urls import path

app_name = 'trips'

urlpatterns = [
    path('triplist/', views.TripListView.as_view(), name='triplist'),
    path('triplist/<slug:slug>/', views.ActivityView.as_view(), name='activity'),
    path('tripapi/', views.TripApiView.as_view()),
    path('tripapi/<int:pk>/', views.TripDetailApiView.as_view()),
]

如何在表单中添加编辑和删除功能?是否可以使用def update(self, request):def delete(self, request):之类的功能通过TemplateView添加编辑和删除功能?

答案

您需要的是generic editing views。这些包括FormViewCreateViewUpdateViewsDeleteViews。加上ListViewDetailView,对于基本上为您量身定制的项目,您已经获得了95%的视图。

以上是关于Django:使用TemplateView在Django表单中添加编辑和删除功能的问题的主要内容,如果未能解决你的问题,请参考以下文章

Django TemplateView 线程安全

Django:使用TemplateView在Django表单中添加编辑和删除功能的问题

Django TemplateView 与 DetailView

get_template_names(self) 在 TemplateView 中不起作用

authenticate()和login()实现用户登录 | Django

{Django基础八之cookie和session}一 会话跟踪 二 cookie 三 django中操作cookie 四 session 五 dja