如何使用Django formset用外键更新表

时间:2020-04-05 18:06:03

标签: django django-3.0

我有:

1-两种模型:客户模型和联系模型(外键)

2-两种形式,一种用于客户,另一种用于联系人

我在这里要做的是,在同一视图上用他的联系人更新客户端表,因此我必须从客户端数据(外键)中获取联系人数据,然后同时显示两者并使用update方法进行更新

我面临的主要困难是如何从父模型中获取子模型数据并进行更新

有人告诉我,如果有人知道如何在这种情况下实现Django Formset,那我将不胜感激,谢谢

models.py:

class Client_Data(models.Model):
     RC = models.CharField(max_length=50)
     Raison_social = models.CharField(max_length=254)
     NIF = models.CharField(max_length=50,unique=True)
     AI = models.CharField(max_length=50,unique=True)
     NIS = models.CharField(max_length=50,unique=True)
     Banque = models.CharField(max_length=50,unique=True)
     CB = models.CharField(max_length=50)
     adresse = models.CharField(max_length=50)
     slug = models.SlugField(blank=True, unique=True)
     active = models.BooleanField(default=True)


class Contact(models.Model):
     client = models.ForeignKey(Client_Data,blank=True,on_delete=models.CASCADE)
     Nom = models.CharField(max_length=50)
     post = models.CharField(max_length=50)
     Tel = models.CharField(max_length=50)
     email = models.EmailField(max_length=255,unique=True)
     contact_type = models.CharField(default='Client_contact',max_length=50)

views.py


def client_update(request,slug):
    client = get_object_or_404(Client_Data, slug=slug)
    if request.method == 'POST':
        form = ClientForm(request.POST, instance=client)

    else:
        form = ClientForm(instance=client)

    return save_client_form_update(request, form,'Client_Section/partial_client_update_update.html')



def save_client_form(request, form,Contact_form, template_name):
    data = dict()
    if request.method == 'POST':
        if form.is_valid() and Contact_form.is_valid():
            client = form.save()
            contact = Contact_form.save(commit=False)
            contact.client = client
            contact.save()
            form.save()
            Contact_form.save()

            data['form_is_valid'] = True
            books = Client_Data.objects.all()
            data['html_book_list'] = render_to_string('Client_Section/partial_client_c.html', {
                'client': books
            })
        else:
            print(form.errors)
            print(Contact_form.errors)
            data['form_is_valid'] = False
    context = {'form': form,'contact_form':Contact_form}
    data['html_form'] = render_to_string(template_name, context, request=request)
    return JsonResponse(data)



0 个答案:

没有答案