如何将CreateView用于具有来自您已使用createview的第一个模型的主键的模型

时间:2017-05-23 07:56:41

标签: python django

大家好我想尝试创建一个简单的待办事项列表,但是我遇到了一些麻烦,首先我想在其中创建一个任务我想创建一些活动,这就是问题所在我无法完成。 如何使用CreateView结束传递创建活动,从任务创建pk,创建后如何反转相同的任务细节

非常感谢

模型:

from django.db import models
from django.core.urlresolvers import reverse

class List(models.Model):
    title = models.CharField(blank=True, max_length=100)

class  Meta:
    ordering = ['id']

def __str__(self):
    return self.title

def get_absolute_url(self):
    return reverse('task-detail', kwargs={'pk': self.pk})


PRIORITY_CHOICES = (
    (1, 'Low'),
    (2, 'Normal'),
    (3, 'High')
)

class Item(models.Model):
    title = models.CharField(blank=True, max_length=100)
    created = models.DateTimeField(auto_now=False, auto_now_add=True)
    updated = models.DateTimeField(auto_now=True, auto_now_add=False)
    priority = models.IntegerField(choices=PRIORITY_CHOICES, default=2)
    completed = models.BooleanField(default=False)
    todo_list = models.ForeignKey(List)

class Meta:
    ordering = ['-priority', 'title']

的观点:

class TaskDetailView(DetailView):
    model = List

class TaskCreateView(CreateView):
    model = List
    fields = ['title']
    success_url = '/home'

class TaskUpdateView(UpdateView):
    model = List
    fields = ['title']
    template_name = 'core/update.html'
    success_url = '/home'

class TaskDeleteView(DeleteView):
    model = List
    success_url = reverse_lazy('home')


class ActivityCreateView(CreateView):
    model = Item
    fields = 'title', 'priority', 'completed'
    success_url = '/home'

class ActivityUpdateView(UpdateView):
    model = Item
    fields = 'title', 'priority', 'completed'
    template_name = 'core/update_actvity.html'
    success_url = '/home'

class ActivityDeleteView(DeleteView):
    model = Item
    success_url = reverse_lazy('home')

url:

from django.conf.urls import url, include
from django.contrib import admin
from core.views import ActivityCreateView, ActivityDeleteView, ActivityUpdateView
from core.views import TaskDetailView, TaskCreateView, TaskUpdateView, TaskDeleteView, Home, MyView


urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^accounts/', include('allauth.urls')),
    url(r'^$', Home.as_view(), name="index" ),
    url(r'^home/$', MyView.as_view(), name="home" ),
    url(r'^task/(?P<pk>[0-9]+)/$', TaskDetailView.as_view(), name='task-detail'),
    url(r'^task/(?P<pk>[0-9]+)/update/$', TaskUpdateView.as_view(), name='task-update'),
    url(r'^task/(?P<pk>[0-9]+)/delete/$', TaskDeleteView.as_view(), name='task-delete'),
    url(r'^task/add/$', TaskCreateView.as_view(), name='task-create'),

2 个答案:

答案 0 :(得分:0)

在表单中,您可以为父列表定义隐藏输入,然后在form_valid方法中使用该pk检索父级...例如:

class ItemModelForm(forms.ModelForm):
    list_pk = forms.IntegerField(widget=forms.HiddenInput)

class Meta:
    model = Item
    fields = ['...']

然后:

def form_valid(self, form):
    parent_list = List.objects.get(pk=form.cleaned_data['list_pk'])
    ...
    ...

答案 1 :(得分:0)

环境:

Request Method: POST
Request URL: http://localhost:8000/task/activity/add/

Django Version: 1.11.1
Python Version: 3.5.2
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.sites',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'allauth',
'allauth.account',
'allauth.socialaccount',
'crispy_forms',
'core']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback:

File "/home/diogo/Desktop/todo-list/venv/lib/python3.5/site-    packages/django/core/handlers/exception.py" in inner

41。 response = get_response(request)

File "/home/diogo/Desktop/todo-list/venv/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response

187。 response = self.process_exception_by_middleware(e,request)

File "/home/diogo/Desktop/todo-list/venv/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response

185。 response = wrapped_callback(request,* callback_args,** callback_kwargs)

File "/home/diogo/Desktop/todo-list/venv/lib/python3.5/site-packages/django/views/generic/base.py" in view

68。 return self.dispatch(request,* args,** kwargs)

File "/home/diogo/Desktop/todo-list/venv/lib/python3.5/site-packages/django/views/generic/base.py" in dispatch

88。返回处理程序(request,* args,** kwargs)

File "/home/diogo/Desktop/todo-list/venv/lib/python3.5/site-packages/django/views/generic/edit.py" in post

217。 return super(BaseCreateView,self).post(request,* args,** kwargs)

File "/home/diogo/Desktop/todo-list/venv/lib/python3.5/site-packages/django/views/generic/edit.py" in post

183。 return self.form_valid(form)

File "/home/diogo/Desktop/todo-list/src/core/views.py" in form_valid

63。 parent_list = List.objects.get(pk = form.cleaned_data ['list_pk'])

Exception Type: KeyError at /task/activity/add/
Exception Value: 'list_pk'