Can't see model attribute in Django-admin - python

I changed models.py adding through-model for one of my old models. I't UserProfileLanguage which is a relation between UserProfile, Language and Level. Each UserProfile can have multiple Languages on different Levels (skills).
Now I looked at the Django-admin to see whether I can add manualy Languages with their Levels to the UserProfile but I can't see it there.
Do you know where could be the problem?
I've commented the attribute languages in UserProfile model so you can see it.
Here is my models.py:
from __future__ import unicode_literals
# from django.contrib.auth.base_user import AbstractBaseUser
from django.contrib.auth.models import User
from django.db import models
class AdminContact(models.Model):
email = models.EmailField()
telephone = models.CharField(max_length=40)
def __unicode__(self):
return self.email
class Language(models.Model):
shortcut = models.CharField(max_length=40)
name = models.CharField(max_length=40)
def __str__(self):
return self.name
class Level(models.Model):
LEVEL_CHOICES = (
('standard','Standard level'),
('professional','Professional level'),
('native','Native speaker level'),
)
name = models.CharField(max_length=40,choices=LEVEL_CHOICES, blank=False, null=False)
price_multiplier = models.FloatField()
class UserProfile(models.Model):
user = models.OneToOneField(User, related_name='userprofile')
date_of_birth = models.DateField(null=True,blank=True)
telephone = models.CharField(max_length=40,null=True,blank=True)
IBAN = models.CharField(max_length=40,null=True,blank=True)
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
MARITAL_STATUS_CHOICES = (
('single', 'Single'),
('married', 'Married'),
('separated', 'Separated'),
('divorced', 'Divorced'),
('widowed', 'Widowed'),
)
marital_status = models.CharField(max_length=40, choices=MARITAL_STATUS_CHOICES, null=True, blank=True)
HOW_DO_YOU_KNOW_ABOUT_US_CHOICES = (
('coincidence', u'It was coincidence'),
('relative_or_friends', 'From my relatives or friends'),
)
how_do_you_know_about_us = models.CharField(max_length=40, choices=HOW_DO_YOU_KNOW_ABOUT_US_CHOICES, null=True,
blank=True)
# TRANSLATOR ATTRIBUTES
is_translator = models.BooleanField(default=False)
language_tuples = models.ManyToManyField(LanguageTuple,blank=True)
# I CANT SEE THIS ATTRIBUTE <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
languages = models.ManyToManyField(Language, through='UserProfileLanguage')
rating = models.IntegerField(default=0)
number_of_ratings = models.BigIntegerField(default=0)
def __unicode__(self):
return '{} {}'.format(self.user.first_name, self.user.last_name)
def __str__(self):
return '{} {}'.format(self.user.first_name, self.user.last_name)
class UserProfileLanguage(models.Model):
userprofile = models.ForeignKey(UserProfile)
language = models.ForeignKey(Language)
level = models.ForeignKey(Level)
class Meta:
unique_together = (('userprofile', 'language'),)
class Job(models.Model):
customer = models.ForeignKey(User, related_name='orders')
translator = models.ForeignKey(User, related_name='jobs',null=True)
price = models.FloatField(null=True,blank=True)
# ZADAVA CUSTOMER
description = models.TextField()
file = models.FileField(null=True,blank=True)
language_tuple = models.ForeignKey(LanguageTuple,related_name='jobs')
specialist = models.BooleanField(blank=True)
# AUTOMATICKY GENEROVANE
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
is_active = models.BooleanField(default=False)
is_done = models.BooleanField(default=False)
#property
def has_translator(self):
return self.translator_id is not None
def __str__(self):
return '{}: {}'.format(self.customer,self.language_tuple)

Related

Creating a Django Model for a recipe #3 [duplicate]

Will you help me to figure out why Django raises this error?
SolutionsForLanguagesApp.LanguageLevel: (fields.E336) The model is
used as an in termediate model by
'SolutionsForLanguagesApp.UserProfile.languages', but it does not
have a foreign key to 'UserProfile' or 'Language'.
I'm confused because, as you can see, there is a foreign key to Language in LanguageLevel already:
class LanguageLevel(models.Model):
language = models.ForeignKey(Language)
level = models.ForeignKey(Level)
class Meta:
unique_together = (('level', 'language'),)
Do you know what to do?
EDIT - Added UserProfile:
class UserProfile(models.Model):
user = models.OneToOneField(User, related_name='userprofile')
date_of_birth = models.DateField(null=True, blank=True)
telephone = models.CharField(max_length=40, null=True, blank=True)
IBAN = models.CharField(max_length=40, null=True, blank=True)
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
MARITAL_STATUS_CHOICES = (
('single', 'Single'),
('married', 'Married'),
('separated', 'Separated'),
('divorced', 'Divorced'),
('widowed', 'Widowed'),
)
marital_status = models.CharField(max_length=40, choices=MARITAL_STATUS_CHOICES, null=True, blank=True)
HOW_DO_YOU_KNOW_ABOUT_US_CHOICES = (
('coincidence', u'It was coincidence'),
('relative_or_friends', 'From my relatives or friends'),
)
how_do_you_know_about_us = models.CharField(max_length=40, choices=HOW_DO_YOU_KNOW_ABOUT_US_CHOICES, null=True,
blank=True)
# TRANSLATOR ATTRIBUTES
is_translator = models.BooleanField(default=False)
# language_tuples = models.ManyToManyField(LanguageTuple,blank=True)
languages = models.ManyToManyField(Language, through='LanguageLevel')
rating = models.IntegerField(default=0)
number_of_ratings = models.BigIntegerField(default=0)
def __unicode__(self):
return '{} {}'.format(self.user.first_name, self.user.last_name)
def __str__(self):
return '{} {}'.format(self.user.first_name, self.user.last_name)
Your LanguageLevel model is missing a ForeignKey to the UserProfile:
class LanguageLevel(models.Model):
language = models.ForeignKey(Language)
level = models.ForeignKey(Level)
# Add Foreign Key to UserProfile
userprofile = models.ForeignKey(UserProfile)
class Meta:
unique_together = (('level', 'language'),)
Also I'm not sure that the unique_together constraint is what you want - it will mean that only one user can have any one combination of language/level. A more likely constraint would be ('userprofile', 'language') so that a language can only be mapped to a user once.

Error Submitting a form in Django - django.db.utils.IntegrityError: NOT NULL constraint failed: account_deal.company_id

I'm working on a form that takes value from another model, and everything is loaded correctly, but when I submit the data the form is showing the following error:
django.db.utils.IntegrityError: NOT NULL constraint failed: account_deal.company_id
The consensus is that you have to add blank=True,null=True but that only prevents the error if the user doesn't type any data, in this case, I'm using an auto-generated date, so not sure why am I getting this error.
views.py
def close_lead(request):
if request.method == 'POST':
deal_form = DealForm(request.POST)
if deal_form.is_valid():
deal_form.save()
messages.success(request, 'You have successfully updated the status from open to Close')
id = request.GET.get('project_id', '')
obj = Leads.objects.get(project_id=id)
obj.status = "Closed"
obj.save(update_fields=['status'])
return HttpResponseRedirect(reverse('dashboard'))
else:
messages.error(request, 'Error updating your Form')
else:
id = request.GET.get('project_id', '')
obj = get_object_or_404(Leads, project_id=id)
m = obj.__dict__
keys = Leads.objects.get(project_id=m['project_id'])
form_dict = {'project_id':keys.project_id,
'agent':keys.agent,
'client':keys.point_of_contact,
'company':keys.company,
'service':keys.services
}
form = NewDealForm(request.POST or None,initial = form_dict)
return render(request,
"account/close_lead.html",
{'form':form})
models.py
from django.db import models
from django.conf import settings
from django_countries.fields import CountryField
from phone_field import PhoneField
from djmoney.models.fields import MoneyField
from ckeditor.fields import RichTextField
from django.utils import timezone
class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
email = models.EmailField(blank=True,null=True, unique=True)
role = models.TextField(blank=True)
location = models.TextField(blank=True)
photo = models.ImageField(upload_to='users/%Y/%m/%d', blank=True)
def __str__(self):
return self.user.username
class Company(models.Model):
id = models.BigAutoField(primary_key=True)
company = models.CharField(blank=True, max_length=30, unique=True)
def __str__(self):
return self.company
class Client(models.Model):
id = models.BigAutoField(primary_key=True)
firstname = models.CharField(blank=True, max_length=30)
lastname = models.CharField(blank=True, max_length=15)
company = models.ForeignKey(Company, on_delete=models.CASCADE)
position = models.CharField(blank=True, max_length=50)
country = CountryField(blank_label='(select country)')
email = models.EmailField(blank=True, max_length=100, default="this_is#n_example.com", unique=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
phone = PhoneField(default="(XX)-XXX-XXX")
def __str__(self):
return f'{self.firstname} {self.lastname}'
class Leads(models.Model):
CHOICES = (
('Illumination Studies','Illumination Studies'),
('Training','Training'),
('Survey Design','Survey Design'),
('Software License','Software License')
)
STATUS = (('Open','Open'),
('Closed','Closed'),
('Canceled', 'Canceled')
)
project_id = models.BigAutoField(primary_key=True)
company = models.ForeignKey(Company, on_delete=models.CASCADE)
agent = models.ForeignKey(Profile, on_delete=models.CASCADE, default="agent")
created_at = models.DateTimeField(auto_now_add=True)
point_of_contact = models.ForeignKey(Client, on_delete=models.CASCADE)
expected_revenue = MoneyField(max_digits=14, decimal_places=2, default_currency='USD')
expected_licenses = models.IntegerField(blank=True)
country = CountryField(blank_label='(select country)')
status = models.CharField(max_length=10,choices=STATUS)
estimated_closing_date = models.DateField(blank=True)
services = models.CharField(max_length=20,choices=CHOICES)
def __str__(self):
return f'{self.project_id}'
class CallReport(models.Model):
CHOICES = (
('Phone Call','Phone Call'),
('Onsite Meeting', 'Onsite Meeting'),
('Client Offices', "Client Offices"),
('Other Location','Other Location'),
)
id = models.BigAutoField(primary_key=True)
company = models.ForeignKey(Company, on_delete=models.CASCADE)
minutes_of_meeting = RichTextField(blank=True, null=True)
client_POC = models.CharField(max_length=100)
location = models.CharField(max_length=50,choices=CHOICES, default='Phone Call')
title = models.CharField(max_length=100)
date = models.DateField()
ACTeQ_representative = models.ForeignKey(Profile, on_delete=models.CASCADE, default='agent')
def __str__(self):
return f'Call Report for {self.company}, on the {self.date}'
class Deal(models.Model):
CHOICES = (
('Illumination Studies','Illumination Studies'),
('Training','Training'),
('Survey Design','Survey Design'),
('Software License','Software License')
)
project_id = models.ForeignKey(Leads, on_delete=models.CASCADE, default="project_id")
agent = models.ForeignKey(Profile, on_delete=models.CASCADE, default="agent")
service = models.CharField(max_length=20,choices=CHOICES)
closing_date = models.DateField(auto_now_add=True)
client = models.ForeignKey(Client, on_delete=models.CASCADE,default='client')
licenses = models.IntegerField(blank=True)
revenue = MoneyField(max_digits=14, decimal_places=2, default_currency='USD')
comments = models.TextField(blank=True,null=True)
company = models.ForeignKey(Company, on_delete=models.CASCADE)
date = models.DateTimeField(auto_now_add=True)
Lastly, the form:
from .models import Profile, Client, Company, Leads, CallReport, Deal
from django import forms
from django.contrib.auth.models import User
from django.contrib.admin.widgets import AdminDateWidget
from django.forms.fields import DateField
class DateInput(forms.DateInput):
input_type = 'date'
class UserEditForm(forms.ModelForm):
class Meta:
model = User
fields = ('first_name', 'last_name', 'email')
class ProfileEditForm(forms.ModelForm):
class Meta:
model = Profile
fields = ('role', 'photo', 'location')
class ClientForm(forms.ModelForm):
class Meta:
model = Client
fields = ('firstname', 'lastname',"position",'company','country','email','phone')
class CompanyForm(forms.ModelForm):
class Meta:
model = Company
fields = ('company',)
class LeadsForm(forms.ModelForm):
class Meta:
model = Leads
fields = ('project_id','company','agent','point_of_contact','services','expected_licenses',
'expected_revenue','country', 'status', 'estimated_closing_date'
)
widgets = {'estimated_closing_date': DateInput()}
class CallForm(forms.ModelForm):
class Meta:
model = CallReport
fields = ('company','title','location', 'ACTeQ_representative','client_POC','minutes_of_meeting','date')
widgets = {'date':DateInput()}
class DealForm(forms.ModelForm):
class Meta:
model = Deal
fields = ['agent','project_id','service','client', 'licenses','revenue', 'comments']
class EditLeadsForm(forms.ModelForm):
class Meta:
model = Leads
fields = ('project_id','company','agent','point_of_contact','expected_revenue',
'expected_licenses','country', 'status', 'estimated_closing_date',
'services')
widgets = {'date': DateInput()}
class NewDealForm(forms.ModelForm):
class Meta:
model = Deal
fields = ['project_id','agent','client','company','service', 'licenses','revenue', 'comments']
I have already deleted the database and run the migrations, and the error persists.

Django: How to import model from same app?

I've an app called lists.
This has 3 main models: List, ListItem and School.
Every list could be related to 1 school, or this field could be empty.
But when I'm trying to update my model List to have a school field I'm getting:
ImportError: cannot import name 'School' from 'lists.models' (D:\web_proyects\scolarte\lists\models.py)
(scolarte)
Even thought both models are in the same models.py file.
I've tried:
from .models import School
And:
from lists.models import School
lists/models.py:
from django.db import models
from products.models import Product
from roles.models import User
from .models import School
# Create your models here.
class List(models.Model):
LISTA_STATUS = (
('recibida_pagada', 'Recibida y pagada'),
('recibida_no_pagada', 'Recibida pero no pagada'),
('en_revision', 'En revision'),
('en_camino', 'En camino'),
('entregada', 'Entregada'),
('cancelada', 'Cancelada')
)
lista_id = models.CharField(max_length=100)
name = models.CharField(max_length=100)
user = models.OneToOneField(User, on_delete=models.CASCADE)
school = models.OneToOneField(School, on_delete=models.CASCADE)
status = models.CharField(max_length=20, choices=LISTA_STATUS, default='recibida_pagada')
created_at = models.DateTimeField(auto_now_add=True)
modified_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['created_at']
def __str__(self):
return str(self.id)
class ListItem(models.Model):
lista = models.ForeignKey(List, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
comment = models.CharField(max_length=100, blank=True, null=True, default='')
uploaded_at = models.DateTimeField(auto_now_add=True)
step_two_complete = models.BooleanField(default=False)
def sub_total(self):
return int(self.product.price)
class School(models.Model):
name = models.CharField(max_length=100)
address = models.CharField(max_length=100, blank=False)
address_reference = models.CharField(max_length=100, blank=False)
provincia = models.CharField(max_length=100, blank=False, null=True)
canton = models.CharField(max_length=100, blank=False, null=True)
parroquia = models.CharField(max_length=100, blank=False, null=True)
created_at = models.DateTimeField(auto_now_add=True)
modified_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['created_at']
def __str__(self):
return str(self.name)
You don't need to import School since its already in the same model. However you do need to define School first before you can then reference it in another class in the same model file. Update your model so School is defined before List
from django.db import models
from products.models import Product
from roles.models import User
from .models import School
# Create your models here.
class School(models.Model):
name = models.CharField(max_length=100)
address = models.CharField(max_length=100, blank=False)
address_reference = models.CharField(max_length=100, blank=False)
provincia = models.CharField(max_length=100, blank=False, null=True)
canton = models.CharField(max_length=100, blank=False, null=True)
parroquia = models.CharField(max_length=100, blank=False, null=True)
created_at = models.DateTimeField(auto_now_add=True)
modified_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['created_at']
def __str__(self):
return str(self.name)
class List(models.Model):
LISTA_STATUS = (
('recibida_pagada', 'Recibida y pagada'),
('recibida_no_pagada', 'Recibida pero no pagada'),
('en_revision', 'En revision'),
('en_camino', 'En camino'),
('entregada', 'Entregada'),
('cancelada', 'Cancelada')
)
lista_id = models.CharField(max_length=100)
name = models.CharField(max_length=100)
user = models.OneToOneField(User, on_delete=models.CASCADE)
school = models.OneToOneField(School, on_delete=models.CASCADE)
status = models.CharField(max_length=20, choices=LISTA_STATUS, default='recibida_pagada')
created_at = models.DateTimeField(auto_now_add=True)
modified_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['created_at']
def __str__(self):
return str(self.id)
class ListItem(models.Model):
lista = models.ForeignKey(List, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
comment = models.CharField(max_length=100, blank=True, null=True, default='')
uploaded_at = models.DateTimeField(auto_now_add=True)
step_two_complete = models.BooleanField(default=False)
def sub_total(self):
return int(self.product.price)

Can't inline User fields to UserProfile admin tab - 'auth.User' has no ForeignKey to 'MyApp.UserProfile'

I'm trying to add User fields into User Profile admin tab to be able to change every User attribute in one tab. The problem is that the cmd returns:
EDIT: Edited code according to Shang Wang's comment but still raises error:
<class 'MyApp.admin.UserProfileUserInline'>: (admin.E202) 'auth.User' has no ForeignKey to 'MyApp.UserProfile'.
In fact, I want to have either User inlined in UserProfile or UserProfile in User. The problem is that UserProfile has field language (note that this is not a Language model) which is through-model and I can't figure out how to inline it into the User (UserProfile can be inlined without problems), so I'm trying to inline User into UserProfile.
Admin.py:
from django.contrib import admin
from models import *
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
admin.site.register(AdminContact)
class UserProfileInline(admin.StackedInline):
model = UserProfile
can_delete = False
verbose_name_plural = 'User_Profile'
readonly_fields = ('languages',)
class UserProfileLanguageLevelInline(admin.TabularInline):
model = UserProfileLanguage
class UserAdmin(BaseUserAdmin):
inlines = (UserProfileInline, )
class UserProfileUserInline(admin.StackedInline):
model = User
class UserProfileAdmin(admin.ModelAdmin):
inlines = (UserProfileLanguageLevelInline,User,)
admin.site.unregister(User)
admin.site.register(User,UserAdmin)
admin.site.register(LanguageTuple)
admin.site.register(Language)
admin.site.register(Job)
admin.site.register(UserProfileLanguage)
admin.site.register(Level)
admin.site.register(UserProfile,UserProfileAdmin)
Models.py:
from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.db import models
class AdminContact(models.Model):
email = models.EmailField()
telephone = models.CharField(max_length=40)
def __unicode__(self):
return self.email
class Language(models.Model):
shortcut = models.CharField(max_length=40)
name = models.CharField(max_length=40)
def __str__(self):
return self.name
class LanguageTuple(models.Model):
language_from = models.ForeignKey(Language, related_name='language_from', null=True)
language_to = models.ForeignKey(Language, related_name='language_to', null=True)
def __str__(self):
return '{} to {}'.format(self.language_from, self.language_to)
class Level(models.Model):
LEVEL_CHOICES = (
('unknown','Unknown'),
('standard','Standard level'),
('professional','Professional level'),
('native','Native speaker level'),
)
name = models.CharField(max_length=40,choices=LEVEL_CHOICES, blank=False, null=False)
price_multiplier = models.FloatField()
def __str__(self):
return self.get_name_display()
class UserProfile(models.Model):
user = models.OneToOneField(User, related_name='userprofile')
date_of_birth = models.DateField(null=True,blank=True)
telephone = models.CharField(max_length=40,null=True,blank=True)
IBAN = models.CharField(max_length=40,null=True,blank=True)
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
MARITAL_STATUS_CHOICES = (
('single', 'Single'),
('married', 'Married'),
('separated', 'Separated'),
('divorced', 'Divorced'),
('widowed', 'Widowed'),
)
marital_status = models.CharField(max_length=40, choices=MARITAL_STATUS_CHOICES, null=True, blank=True)
HOW_DO_YOU_KNOW_ABOUT_US_CHOICES = (
('coincidence', u'It was coincidence'),
('relative_or_friends', 'From my relatives or friends'),
)
how_do_you_know_about_us = models.CharField(max_length=40, choices=HOW_DO_YOU_KNOW_ABOUT_US_CHOICES, null=True,
blank=True)
# TRANSLATOR ATTRIBUTES
is_translator = models.BooleanField(default=False)
# language_tuples = models.ManyToManyField(LanguageTuple,blank=True)
languages = models.ManyToManyField(Language, through='UserProfileLanguage')
rating = models.IntegerField(default=0)
number_of_ratings = models.BigIntegerField(default=0)
def __unicode__(self):
return '{} {}'.format(self.user.first_name, self.user.last_name)
def __str__(self):
return '{} {}'.format(self.user.first_name, self.user.last_name)
class UserProfileLanguage(models.Model):
userprofile = models.ForeignKey(UserProfile)
language = models.ForeignKey(Language)
level = models.ForeignKey(Level)
class Meta:
unique_together = (('userprofile', 'language'),)
class Job(models.Model):
customer = models.ForeignKey(User, related_name='orders')
translator = models.ForeignKey(User, related_name='jobs',null=True)
price = models.FloatField(null=True,blank=True)
# ZADAVA CUSTOMER
description = models.TextField()
file = models.FileField(null=True,blank=True)
language_tuple = models.ForeignKey(LanguageTuple,related_name='jobs')
specialist = models.BooleanField(blank=True)
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
is_active = models.BooleanField(default=False)
is_done = models.BooleanField(default=False)
#property
def has_translator(self):
return self.translator_id is not None
def __str__(self):
return '{}: {}'.format(self.customer,self.language_tuple)
You shouldn't have User model in inlines for UserProfileAdmin, because User is a model not an inline admin. Edit it like this:
class UserProfileAdmin(admin.ModelAdmin):
inlines = (UserProfileLanguageLevelInline, UserProfileUserInline)

django_select2, Model object is not iterable

I'm getting a "'Document' object is not iterable" error when this form is submitted. It works if 'document' is just taken from the model rather than written with the select2 package. It's extremely similar to the example code from the django_select2 package. I've tried making it Document.objects.all() instead, and that didn't work either.
models.py
class Individual(models.Model):
id = models.CharField(max_length=8, unique=True, verbose_name='ID')
first_name = models.CharField(max_length=50, null=True)
middle_name = models.CharField(max_length=50, blank=True, null=True)
last_name = models.CharField(max_length=100, null=True)
dob = models.CharField(max_length=15, blank=True)
suffix = models.CharField(max_length=25, blank=True, null=True)
time_stamp = models.DateTimeField(auto_now=True)
entered_by = models.CharField(max_length=50)
def _name(self):
return self.first_name + ' ' + self.last_name
class Meta:
db_tablespace = 'name_of_database'
def __unicode__(self):
return self.id
class Document(models.Model):
document_name = models.CharField(max_length=100)
class Meta:
db_tablespace = 'name_of_database'
def __unicode__(self):
return self.document_name
class DocLog(models.Model):
individual = models.ForeignKey('Individual', to_field='id', null=True)
fiscal = models.PositiveIntegerField(db_index=True)
document = models.ManyToManyField(Document, max_length=50,
verbose_name='Document Title')
date_received = models.DateField(editable=True, verbose_name='Date Received')
doc_notes = models.TextField(max_length=500, verbose_name='Document Notes')
time_stamp = models.DateTimeField(auto_now=True)
entered_by = models.CharField(max_length=50)
class Meta:
db_tablespace = 'name_of_database'
verbose_name = 'Document Log'
def __unicode__(self):
return self.individual.id
forms.py
from django import forms
from django_select2 import *
from .models import DocLog, Document
#Document Select2 class
class DocumentChoices(AutoModelSelect2Field):
queryset = Document.objects
search_fields = ['document_name__icontains',]
#New document form
class NewDocument(forms.ModelForm):
document = DocumentChoices()
class Meta:
model = DocLog
fields = ('individual', 'fiscal', 'document', 'date_received', 'doc_notes')
widgets = {
'individual': forms.HiddenInput(),
}
You defined ManyToManyField in your Model, in Modelform ManyToManyField is represented by django.forms.ModelMultipleChoiceField, which is a MultipleChoiceField whose choices are a model QuerySet.
So instead of using AutoModelSelect2Field you use AutoModelSelect2MultipleField
for your case
#Document Select2 class
class DocumentChoices(AutoModelSelect2MultipleField):
queryset = Document.objects
search_fields = ['document_name__icontains',]

Categories

Resources