在Django CBV中使用外键相关模型创建和UpdateView

时间:2018-08-27 20:50:16

标签: django django-models django-forms django-class-based-views

我有1个带有2个模型的应用程序“ portfolio”,第二个具有第一个FK,我需要(创建和更新)该视图。我对第一个模型有完整的CRUD,但是我不知道要使用fk模型获得相同的结果。我正在寻找两者的创建和更新视图。但是我无法以专辑形式访问proyects,所以用这种方式从项目中选择FK,以将相关专辑与创建的所有项目之一相联系

models.py

from django.db import models
from django.contrib.auth.models import User
from ckeditor.fields import RichTextField

# Create your models here.

class Project(models.Model):
    user = models.ForeignKey(User, on_delete = models.CASCADE, default=1)
    name = models.CharField(verbose_name='Nombre del proyecto', max_length=200)
    client = models.CharField(verbose_name='Nombre del cliente', max_length=200)
    description = RichTextField(verbose_name='Descripción')
    start = models.DateField(verbose_name='Fecha de Inicio', null=True, blank=True)
    ending = models.DateField(verbose_name='Fecha de Finalización', null=True, blank=True)
    order = models.SmallIntegerField(verbose_name="Orden", default=0)
    created = models.DateTimeField(verbose_name='Fecha de creación', auto_now_add=True)
    updated = models.DateTimeField(verbose_name='Fecha de modificación', auto_now=True)

    class Meta:
        verbose_name = 'Proyecto'
        verbose_name_plural = 'Proyectos'
        ordering = ['-start', 'order']

    def __str__(self):
        return self.name

class Album(models.Model):
    project = models.ForeignKey(Project, on_delete = models.CASCADE)
    title = models.CharField(verbose_name='Título de la imagen', max_length=200, null=True, blank=True)
    image = models.ImageField(verbose_name='Imagen', upload_to='portfolio')
    created = models.DateTimeField(verbose_name='Fecha de creación', auto_now_add=True)
    updated = models.DateTimeField(verbose_name='Fecha de modificación', auto_now=True)

    class Meta:
        verbose_name = 'Imagen en el album'
        verbose_name_plural = 'Imágenes en el album'
        ordering = ['created']

        def __str__(self):
            return self.title

views.py

@method_decorator(staff_member_required(login_url='login'), name='dispatch')
class ProjectCreateView(CreateView):
    model = Project
    template_name = "core/project_create_form.html"
    form_class = ProjectCreateForm
    success_url = reverse_lazy('home')

@method_decorator(staff_member_required(login_url='login'), name='dispatch')
class ProjectUpdateView(UpdateView):
    model = Project
    template_name = "core/project_update_form.html"
    form_class = ProjectUpdateForm


@method_decorator(staff_member_required(login_url='login'), name='dispatch')
class ProjectDeleteView(DeleteView):
    model = Project
    template_name = "core/project_delete_form.html"
    success_url = reverse_lazy('home')

forms.py

class ProjectCreateForm(forms.ModelForm):

    template_name = 'core/project_create_form.html'

    class Meta:
        model = Project
        fields = [
            'name',
            'client',
            'description',
            'start',
            'ending',
            'order',
            ]

        widgets = {

            'name':forms.TextInput(
                attrs={
                    'class':'form-control'}),

            'client':forms.TextInput(
                attrs={
                    'class':'form-control'}),

            'description':forms.Textarea(
                attrs={
                    'class':'form-control'}),

            'start':forms.DateInput(
                attrs={
                    'class':'form-control'}),

            'ending':forms.DateInput(
                attrs={
                    'class':'form-control'}),

            'order':forms.NumberInput(
                attrs={
                    'class':'form-control'}),
        }


class ProjectUpdateForm(forms.ModelForm):

    template_name = 'core/project_update_form.html'

    class Meta:
        model = Project
        fields = [
            'name',
            'client',
            'description',
            'start',
            'ending',
            'order',
            ]

        widgets = {

            'name':forms.TextInput(
                attrs={
                    'class':'form-control'}),

            'client':forms.TextInput(
                attrs={
                    'class':'form-control'}),

            'description':forms.Textarea(
                attrs={
                    'class':'form-control'}),

            'start':forms.DateInput(
                attrs={
                    'class':'form-control'}),

            'ending':forms.DateInput(
                attrs={
                    'class':'form-control'}),

            'order':forms.NumberInput(
                attrs={
                    'class':'form-control'}),
        }

1 个答案:

答案 0 :(得分:0)

我还没有尝试过该库,但是它可能会解决您的问题,Django中的一个常见问题是如何拥有视图,尤其是基于类的视图,该视图可以一次显示和处理多种表单。 https://github.com/kennethlove/django-shapeshifter