Я получаю сообщение об ошибке
'ValueError: Невозможно назначить' '2' ': «Lead.category» должен быть экземпляром «Category».
в views.py on line form.is_valid()
.
Я знаю, как создать экземпляр Category, но не знаю, где его применить. Пожалуйста, помогите
views.py
def create_lead(request):
template_name = "create_lead.html"
users = []
if request.user.role == 'ADMIN' or request.user.is_superuser:
users = User.objects.filter(is_active=True).order_by('email')
elif request.user.google.all():
users = []
else:
users = User.objects.filter(role='ADMIN').order_by('email')
form = LeadForm(assigned_to=users)
if request.POST:
form = LeadForm(request.POST, request.FILES, assigned_to=users)
if form.is_valid():
lead_obj = form.save(commit=False)
lead_obj.created_by = request.user
lead_obj.save()
if request.POST.get('tags', ''):
tags = request.POST.get("tags")
splitted_tags = tags.split(",")
for t in splitted_tags:
tag = Tags.objects.filter(name=t)
if tag:
tag = tag[0]
else:
tag = Tags.objects.create(name=t)
lead_obj.tags.add(tag)
if request.POST.getlist('assigned_to', []):
lead_obj.assigned_to.add(*request.POST.getlist('assigned_to'))
assigned_to_list = request.POST.getlist('assigned_to')
if request.POST.getlist('teams', []):
user_ids = Teams.objects.filter(id__in=request.POST.getlist('teams')).values_list('users', flat=True)
assinged_to_users_ids = lead_obj.assigned_to.all().values_list('id', flat=True)
for user_id in user_ids:
if user_id not in assinged_to_users_ids:
lead_obj.assigned_to.add(user_id)
if request.POST.getlist('teams', []):
lead_obj.teams.add(*request.POST.getlist('teams'))
if request.POST.getlist('products',[]):
lead_obj.products.add(*request.POST.getlist('products'))
current_site = get_current_site(request)
recipients = list(lead_obj.assigned_to.all().values_list('id', flat=True))
send_email_to_assigned_user.delay(recipients, lead_obj.id, domain=current_site.domain,
protocol=request.scheme)
if request.FILES.get('lead_attachment'):
attachment = Attachments()
attachment.created_by = request.user
attachment.file_name = request.FILES.get(
'lead_attachment').name
attachment.lead = lead_obj
attachment.attachment = request.FILES.get('lead_attachment')
attachment.save()
if request.POST.get('status') == "converted":
account_object = Account.objects.create(
created_by=request.user, name=lead_obj.account_name,
email=lead_obj.email, phone=lead_obj.phone,
description=request.POST.get('description'),
website=request.POST.get('website'),
)
account_object.billing_address_line = lead_obj.address_line
account_object.billing_street = lead_obj.street
account_object.billing_city = lead_obj.city
account_object.billing_state = lead_obj.state
account_object.billing_postcode = lead_obj.postcode
account_object.billing_country = lead_obj.country
for tag in lead_obj.tags.all():
account_object.tags.add(tag)
if request.POST.getlist('assigned_to', []):
# account_object.assigned_to.add(*request.POST.getlist('assigned_to'))
assigned_to_list = request.POST.getlist('assigned_to')
current_site = get_current_site(request)
recipients = assigned_to_list
send_email_to_assigned_user.delay(recipients, lead_obj.id, domain=current_site.domain,
protocol=request.scheme)
account_object.save()
# update_leads_cache.delay()
success_url = reverse('leads:list')
if request.POST.get("savenewform"):
success_url = reverse("leads:add_lead")
return JsonResponse({'error': False, 'success_url': success_url})
return JsonResponse({'error': True, 'errors': form.errors})
context = {}
context["lead_form"] = form
context["accounts"] = Account.objects.filter(status="open")
context["users"] = users
context["countries"] = COUNTRIES
context["status"] = LEAD_STATUS
context["source"] = LEAD_SOURCE
context["teams"] = Teams.objects.all()
context['products'] = Product.objects.all()
context["assignedto_list"] = [
int(i) for i in request.POST.getlist('assigned_to', []) if i]
return render(request, template_name, context)
models.py
class Lead(models.Model):
title = models.CharField(
pgettext_lazy("Treatment Pronouns for the customer",
"Title"), max_length=64)
first_name = models.CharField(_("First name"), null=True, max_length=255)
last_name = models.CharField(_("Last name"), null=True, max_length=255)
email = models.EmailField(null=True, blank=True)
phone = models.CharField(max_length=10,default=0,blank=False,null=False)
status = models.CharField(
_("Status of Lead"),
max_length=255, blank=True,
null=True, choices=LEAD_STATUS)
source = models.CharField(
_("Source of Lead"), max_length=255,
blank=True, null=True, choices=LEAD_SOURCE)
address_line = models.CharField(
_("Address"), max_length=255, blank=True, null=True)
street = models.CharField(
_("Street"), max_length=55, blank=True, null=True)
city = models.CharField(_("City"), max_length=255, blank=True, null=True)
state = models.CharField(_("State"), max_length=255, blank=True, null=True)
postcode = models.CharField(
_("Post/Zip-code"), max_length=64, blank=True, null=True)
country = models.CharField(
max_length=3, choices=COUNTRIES, blank=True, null=True)
website = models.CharField(
_("Website"), max_length=255, blank=True, null=True)
description = models.TextField(blank=True, null=True)
assigned_to = models.ManyToManyField(
User, related_name='lead_assigned_users')
account_name = models.CharField(max_length=255, null=True, blank=True)
opportunity_amount = models.DecimalField(
_("Opportunity Amount"),
decimal_places=2, max_digits=12,
blank=True, null=True)
created_by = models.ForeignKey(
User, related_name='lead_created_by',
on_delete=models.SET_NULL, null=True)
created_on = models.DateTimeField(_("Created on"), auto_now_add=True)
is_active = models.BooleanField(default=False)
enquery_type = models.CharField(max_length=255, blank=True, null=True)
tags = models.ManyToManyField(Tags, blank=True)
contacts = models.ManyToManyField(Contact, related_name="lead_contacts")
created_from_site = models.BooleanField(default=False)
teams = models.ManyToManyField(Teams, related_name='lead_teams')
type = models.CharField(max_length=20,choices=TYPE,blank=True,null=True)
products = models.ManyToManyField(Product,related_name='company_products',limit_choices_to=5)
category = models.ForeignKey(Category, default=0, related_name='selected_category',on_delete=models.CASCADE,blank=True,null=True)
sub_category = models.ForeignKey(SubCategory,default=0, related_name='selected_sub_category',on_delete=models.CASCADE,blank=True,null=True)
item_list = models.ForeignKey(ItemList,default=0, related_name='selected_item',on_delete=models.CASCADE,blank=True,null=True)
class Meta:
ordering = ['-created_on']
def __str__(self):
return self.title
forms.py
class LeadForm(forms.ModelForm):
teams_queryset = []
teams = forms.MultipleChoiceField(choices=teams_queryset)
product_queryset = []
products = forms.MultipleChoiceField(choices=product_queryset)
phone = forms.RegexField(max_length=10, regex=r'[0-9]+')
category_choices = [('---------','---------')] + [(cat.get('id'),cat.get('name')) for cat in Category.objects.all().values('id','name')]
category = forms.ChoiceField(choices=category_choices)
# products = forms.ModelMultipleChoiceField(choices=[(pro.get('id'),pro.get('name')) for pro in Product.objects.all().values('id','name')])
def __init__(self, *args, **kwargs):
assigned_users = kwargs.pop('assigned_to', [])
products = kwargs.pop('products',[])
category = kwargs.pop('category',[])
sub_category = kwargs.pop('sub_category',[])
item_list = kwargs.pop('item_list',[])
super(LeadForm, self).__init__(*args, **kwargs)
# print (self.fields.keys())
for field in self.fields.values():
field.widget.attrs = {"class": "form-control"}
if self.data.get('status') == 'converted':
self.fields['account_name'].required = True
self.fields['email'].required = True
self.fields['first_name'].required = False
self.fields['last_name'].required = False
self.fields['title'].required = True
self.fields['sub_category'].queryset = SubCategory.objects.none()
self.fields['item_list'].queryset = ItemList.objects.none()
if 'category' in self.data:
try:
cat_id = int(self.data.get('category'))
self.fields['sub_category'].queryset = SubCategory.objects.filter(id=cat_id).order_by('name')
except (ValueError, TypeError):
pass
elif 'sub_category' in self.data:
try:
subc_id = int(self.data.get('sub_category'))
self.fields['item_list'].queryset = ItemList.objects.filter(id=subc_id).order_by('name')
except (ValueError, TypeError):
pass
elif self.instance.pk:
self.fields['sub_category'].queryset = self.instance.sub_category.city_set.order_by('name')
self.fields['item_list'].queryset = self.instance.item_list.city_set.order_by('name')
if assigned_users:
self.fields['assigned_to'].queryset = assigned_users
if category:
self.fields['category'].queryset = category
if products:
self.fields['products'].queryset = products
self.fields['assigned_to'].required = False
for key, value in self.fields.items():
if key == 'phone':
value.widget.attrs['placeholder'] =\
'Enter phone number with country code'
else:
value.widget.attrs['placeholder'] = value.label
self.fields['first_name'].widget.attrs.update({
'placeholder': 'First Name'})
self.fields['last_name'].widget.attrs.update({
'placeholder': 'Last Name'})
self.fields['account_name'].widget.attrs.update({
'placeholder': 'Account Name'})
self.fields['phone'].widget.attrs.update({
'placeholder': '1234567890'})
self.fields['description'].widget.attrs.update({
'rows': '3'})
self.fields['address_line'].widget.attrs.update({
'placeholder': 'Address Line'})
self.fields['street'].widget.attrs.update({
'placeholder': 'Street'})
self.fields['city'].widget.attrs.update({
'placeholder': 'City'})
self.fields['state'].widget.attrs.update({
'placeholder': 'State'})
self.fields['postcode'].widget.attrs.update({
'placeholder': 'Postcode'})
self.fields["country"].choices = [
("", "--Country--"), ] + list(self.fields["country"].choices)[1:]
self.fields["teams"].choices = [(team.get('id'), team.get('name')) for team in Teams.objects.all().values('id', 'name')]
self.fields["teams"].required = False
self.fields['products'].choices = [(pro.get('id'),pro.get('name')) for pro in Product.objects.all().values('id','name')]
self.fields['category'].choices = self.category_choices
class Meta:
model = Lead
fields = ('assigned_to', 'first_name',
'last_name', 'account_name', 'title',
'phone', 'email', 'status', 'source',
'website', 'description',
'address_line', 'street',
'city', 'state', 'postcode',
'country','type','products',
'category','sub_category','item_list',
)