是否可以在一个视图中保存2个或多个相关模型?在Django?

pdkcd3nj  于 2023-10-21  发布在  Go
关注(0)|答案(1)|浏览(101)

我不知道如何在django中保存多个链接的模型,我试图覆盖get_success_url,但我在死胡同(。我试图确保在保存表单时,保存一个带有基本信息的模型,并将其与电话号码相关联,以及与客户姓名相关联。这一切都是为了让你可以为一个客户端保存几个数字;以后我也想把客户端和客户端的地址连接起来,因为可以有好几个地址。代码如下:

views.py

from .models import Orders, Person, Phone
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
from .forms import OrdersForms, AuthUserForm, RegisterUserForm
from django.urls import reverse, reverse_lazy
from django.contrib import messages
from django.contrib.auth.views import LoginView, LogoutView
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponseRedirect

class OrderCreateView(CustomSuccessMessageMixin, CreateView):
    model = Orders
    template_name = 'create.html'
    form_class = OrdersForms
    success_url = reverse_lazy('data_base')
    success_msg = 'Заявка дабавлена'

    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.author = self.request.user
        self.object.save()
        return super().form_valid(form)

    def get_success_url(self):
        # phone_number = self.request.POST.get('phones')
        name = self.request.POST.get('client_name')
        phone_number = self.request.POST.get('phones')

        id = self.request.POST.get('id')  # ??

        Person.objects.create(client_name=name)
        Phone.objects.create(phone=phone_number, contact=id)  # I don’t know what to put for contact
        return super().get_success_url()

models.py

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

class Person(models.Model):
    client_name = models.CharField(max_length=100, verbose_name='Фио клиента')

    def __str__(self):
        return self.client_name

    class Meta:
        verbose_name = 'Клиент'
        verbose_name_plural = 'Клиенты'

class Phone(models.Model):
    phone = models.CharField(max_length=50, verbose_name='Телефон')
    contact = models.ForeignKey(Person, on_delete=models.CASCADE, related_name='phones', verbose_name='Контакт')

    def __str__(self):
        return self.phone

    class Meta:
        verbose_name = 'Телефон'
        verbose_name_plural = 'Телефоны'

class Orders(models.Model):  # Основная база данных
    objects = None
    author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, verbose_name='Принял', blank=True)
    date_of_creation = models.DateTimeField(auto_now=True, verbose_name='Дата создания')
    execution_date = models.DateField(verbose_name='Дата исполнения')
    address = models.CharField(max_length=200, verbose_name='Адрес')
    service = models.CharField(max_length=100, verbose_name='Услуга')
    master = models.ForeignKey(User, on_delete=models.SET_NULL, related_name='master',  null=True, verbose_name='Мастер', blank=True)
    client = models.ForeignKey(Phone, on_delete=models.SET_NULL, related_name='client',  null=True, verbose_name='Клиент', blank=True)

    def __str__(self):
        return '%s %s %s' % (self.execution_date, self.address, self.service)

    class Meta:
        verbose_name = 'Заявка'
        verbose_name_plural = 'Заявки'


forms.py

from django import forms
from .models import Orders
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth.models import User

class UserFullnameChoiceField(forms.ModelChoiceField):
    def label_from_instance(self, obj):
        return obj.get_full_name()

class OrdersForms(forms.ModelForm):
    master = UserFullnameChoiceField(queryset=User.objects.all(), label='Мастер')
    client_name = forms.CharField(label='Фио клиента')
    phones = forms.CharField(label='Телефон')

    class Meta:
        model = Orders
        fields = ('execution_date', 'address', 'service', 'master', 'client_name', 'phones')

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['master'].empty_label = '-Выберите мастера-'
        # users = User.objects.all()
        # self.fields['master'].choices = [(user.pk, user.get_full_name()) for user in users]
        for field in self.fields:
            self.fields[field].widget.attrs['class'] = 'form-control'

class AuthUserForm(AuthenticationForm, forms.ModelForm):
    class Meta:
        model = User
        fields = ('username', 'password')

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for field in self.fields:
            self.fields[field].widget.attrs['class'] = 'form-control'

class RegisterUserForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ('username', 'password', 'groups')

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for field in self.fields:
            self.fields[field].widget.attrs['class'] = 'form-control'

    def save(self, commit=True):
        user = super().save(commit=False)
        user.set_password(self.cleaned_data["password"])
        if commit:
            user.save()
            if hasattr(self, "save_m2m"):
                self.save_m2m()
        return user

我试图在get_success_url方法中覆盖OrderView。将字段分别保存到表单中,但我不知道如何找到Person模型的id并将其保存到Phone模型中。有可能做到吗?

fae0ux8s

fae0ux8s1#

您可以在 get_success_url 中执行此操作

person = Person.objects.create(client_name=name)
Phone.objects.create(phone=phone_number, contact=person)

方法 create 返回创建的示例,你可以得到它的所有属性,包括 id

相关问题