在表单提交上创建Django模型实例

时间:2018-01-03 04:32:01

标签: python django

我正在努力创建一个"统计数据"我的项目中的应用程序,用于跟踪我的网站生成的所有潜在客户。当用户提交"请求信息"表单消息会自动发送到与该产品关联的业务。同时我想在Stats应用程序中的一个模型中创建一个模型实例(我们正在处理的是不同的应用程序)。 Stats在后台工作,只为某些事情收集信息视图模型实例。这是代码细分:

观点:

def ListingView(request,name_initials,l_slug):
    listing = get_object_or_404(Listing,l_slug=l_slug)
    images = ListingImage.objects.filter(property=listing)
    form = ContactPropertyForm(request.POST or None)

    context = {
            'listing':listing,
            'images':images,
            'form':form,
            }

    if form.is_valid():
        name = form.cleaned_data.get('name')
        phone = form.cleaned_data.get('phone')
        email = form.cleaned_data.get('email')
        party_size = form.cleaned_data.get('party_size')
        form_message = form.cleaned_data.get('message')
        listing_address = listing.address
        message = name + "  " + phone + "   " + email + "   " + party_size + "  " + listing_address
        to_email = ['email here']
        html_message = "<b>Name: </b>" + name + "<br>" + "<b>Phone: </b>" + phone + "<br>" + "<b>Email: </b>" + email + "<br>" + "<b>Group Size: </b>" + party_size + "<br>" + "<b>Property: </b>" + listing_address
        send_mail('New Lead', message, 'from email', ['To email'], fail_silently=False, html_message=html_message)

        Leads.add(lead)
        lead = Leads.objects.create(
            listing = listing_address,
            company = listing.l_company,
            )


    return render(request,'listings/single_listing.html',context)

具体来说,这就是我们正在处理的问题:

Leads.add(lead)
    lead = Leads.objects.create(
        listing = listing_address,
        company = listing.l_company,
        )

我在表单提交时也收到此错误:

AttributeError at /tu/diamond-green-apartments
type object 'Leads' has no attribute 'add'

也许我不打算在单独的应用模型中正确添加模型实例?

旁注:对于上下文,我从之前处理过的另一个项目中调整了它,它是通知系统的一部分。这是它最初的样子:

if user.is_authenticated():
    if user in obj.likes.all():
        obj.likes.remove(user)
    else:
        obj.likes.add(user)
        notification = UserNotification.objects.create(
            fromUser = self.request.user,
            toUser = obj.author,
            post = obj,
            notify_type = "like",
        )

1 个答案:

答案 0 :(得分:1)

Django add方法仅用于将实例添加到多对一或多对多相关对象集。在你的情况下Leads.add(lead)是不必要的,你可以毫无问题地删除它,这一行将自己添加新的Lead对象:

lead = Leads.objects.create(
    listing = listing_address,
    company = listing.l_company,
)