django manytomany user auto fill the user field - python

I have 2 tables in my models.py. I'm trying to auto fill the user filed in the second table whatever user I select in my first table I tried to override the save_model in admins.py but it didn't work. Here is my models.py file:
class Company(models.Model):
company_name = models.CharField(max_length = 50)
slug = models.SlugField(unique = True)
user = models.ManyToManyField(User, related_name='company_user')
objects = models.Manager()
published = PublishedManager()
def __str__(self):
return self.company_name
class Group(models.Model):
company_name = models.ForeignKey(Company, related_name = 'co_name',
on_delete=models.CASCADE)
count = models.CharField(max_length = 50)
real_count = models.CharField(max_length = 50)
entry_date = models.DateTimeField()
exit_date = models.DateTimeField()
code = models.CharField(max_length = 10)
code_date = models.DateTimeField()
manifest = models.ImageField(upload_to='manifest/%m/%y', blank=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
user = models.ManyToManyField(User, related_name='group_user', blank=True)
objects = models.Manager()
published = PublishedManager()
class Meta:
ordering = ('-code_date',)
def __str__(self):
return str(self.id)
my admins.py file
#admin.register(Group)
class GroupAdmin(admin.ModelAdmin):
list_display = ['id', 'company_name', 'code', 'code_date', 'count',
'real_count', 'entry_date', 'exit_date',
'manifest', 'created'
]
autocomplete_fields = ('user',)
#admin.register(Company)
class CompanyAdmin(admin.ModelAdmin):
list_display = ['company_name']
autocomplete_fields = ('user',)
prepopulated_fields = {'slug': ('company_name',)}
views.py
#login_required
def main_approval(request):
groups = Group.objects.filter(user=request.user)
context = {'groups': groups}
return render(request, 'approval/main_list.html', context)
I'm trying to get the user in the Company class to be auto inserted in my Group class
Any advice?

Try to do this in views.py
user = self.company_name.user.all()

Related

django.db.utils.IntegrityError: null value in column "auto_id" of relation "university_university" violates not-null constraint

I am getting a integrity error, I have tried adding null=True to auto id field then its working but auto_id field must not be blank=True or null=True.These models are given by my superiors I am finding this hard to understand
This is the core app models.py
import uuid
from django.db import models
from django.db.models import Max
from django.utils import timezone
from decimal import Decimal
from django.utils.translation import gettext_lazy as _
from django.core.validators import MinValueValidator
from core.utils import DictField
from django.contrib.auth import get_user_model
from django.contrib.humanize.templatetags.humanize import naturaltime
def basedata(self, request):
# Check is create
if self._state.adding:
self.auto_id = (self.__class__.objects.aggregate(max_auto_id=Max('auto_id')).get('max_auto_id') or 0) + 1
if request.user.is_authenticated:
self.creator = request.user
# If updating
if request.user.is_authenticated:
self.updater = request.user
self.date_updated = timezone.now()
class BaseModel(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
auto_id = models.PositiveIntegerField(db_index=True, unique=True)
creator = models.ForeignKey(get_user_model(), blank=True, related_name="creator_%(class)s_objects", limit_choices_to={'is_active': True}, on_delete=models.CASCADE)
updater = models.ForeignKey(get_user_model(), blank=True, related_name="updater_%(class)s_objects", limit_choices_to={'is_active': True}, on_delete=models.CASCADE)
date_added = models.DateTimeField(db_index=True, auto_now_add=True)
date_updated = models.DateTimeField(auto_now_add=True)
is_deleted = models.BooleanField(default=False)
class Meta:
abstract = True
def delete(self):
self.is_deleted = True
self.save()
def delete_with_user(self, user):
self.is_deleted = True
user = self.user
user.username = user.username + '_deleted_' + str(self.id)
user.save()
self.save()
#property
def date_added_natural(self):
return naturaltime(self.date_added)
class Mode(models.Model):
readonly = models.BooleanField(default=False)
maintenance = models.BooleanField(default=False)
down = models.BooleanField(default=False)
class Meta:
db_table = 'mode'
verbose_name = _('mode')
verbose_name_plural = _('mode')
ordering = ('id',)
class Admin:
list_display = ('id', 'readonly', 'maintenance', 'down')
def __str__(self):
return str(self.id)
class AppUpdate(models.Model):
date_added = models.DateTimeField(db_index=True, auto_now_add=True)
app_version = models.CharField(max_length=16)
force_upgrade = models.BooleanField(default=False)
recommended_upgrade = models.BooleanField(default=False)
ios_app_version = models.CharField(max_length=16)
ios_force_upgrade = models.BooleanField(default=False)
ios_recommended_upgrade = models.BooleanField(default=False)
class Meta:
db_table = 'app_update'
verbose_name = _('App update')
verbose_name_plural = _('App updates')
ordering = ('id',)
def __str__(self):
return str(self.id)
This is the university models.py
from django.db import models
from core.models import BaseModel
from versatileimagefield.fields import VersatileImageField
# Create your models here.
class Graduation(BaseModel):
name = models.CharField(max_length=200)
class Meta:
db_table = 'university_graduation'
verbose_name = ('Graduation')
verbose_name_plural = ('Graduation')
ordering = ('auto_id',)
def __str__(self):
return str(self.name)
class University(BaseModel):
title = models.CharField(max_length=200)
location = models.CharField(max_length=200)
location_url = models.URLField()
estd = models.CharField(max_length=4)
ranking = models.CharField(max_length=4)
intake = models.CharField(max_length=3)
acceptance_rate = models.CharField(max_length=3)
teacher_ratio = models.CharField(max_length=3)
about_university = models.TextField()
description = models.TextField()
graduation = models.ManyToManyField(Graduation)
logo = VersatileImageField('Logo', upload_to="university/logo")
image = VersatileImageField('Image', upload_to="university/image")
class Meta:
db_table = 'university_university'
verbose_name = ('University')
verbose_name_plural = ('University')
ordering = ('auto_id',)
def __str__(self):
return str(self.title)
class AdmissionRequirments(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
auto_id = models.PositiveIntegerField(db_index=True, unique=True)
date_added = models.DateTimeField(db_index=True, auto_now_add=True)
date_updated = models.DateTimeField(auto_now_add=True)
university = models.ForeignKey(University, limit_choices_to={'is_deleted': False}, on_delete=models.CASCADE)
requirement = models.CharField(max_length=200)
class Meta:
db_table = 'university_admission_requirements'
verbose_name = ('Admission Requirements')
verbose_name_plural = ('Admission Requirements')
ordering = ('auto_id',)
def __str__(self):
return str(self.id)
class Scholarship(BaseModel):
title = models.CharField(max_length=200)
eligibility = models.CharField(max_length=200)
applicability = models.CharField(max_length=200)
graduation = models.ManyToManyField(Graduation)
university = models.ManyToManyField(University)
class Meta:
db_table = 'university_scholarship'
verbose_name = ('Scholarship')
verbose_name_plural = ('Scholarship')
ordering = ('auto_id',)
def __str__(self):
return str(self.title)
This is the university form.py
from django.forms import forms
from university.models import University, Graduation
from django.contrib.auth.models import User
from django.contrib.auth import get_user
class CreateUniversityForm(forms.Form):
class Meta:
model = University
fields = '__all__'
def save(self):
user = self.cleaned_data.get("user")
university = University(
auto_id = self.cleaned_data.get('id'),
title = self.cleaned_data.get('title'),
location = self.cleaned_data.get('location'),
location_url = self.cleaned_data.get('location_url'),
estd = self.cleaned_data.get('estd'),
ranking = self.cleaned_data.get('ranking'),
intake = self.cleaned_data.get('intake'),
acceptance_rate = self.cleaned_data.get('acceptance_rate'),
teacher_ratio = self.cleaned_data.get('teacher_ratio'),
about_university = self.cleaned_data.get('about_university'),
description = self.cleaned_data.get('description'),
logo = self.cleaned_data.get('logo'),
image = self.cleaned_data.get('image')
)
graduation = Graduation.objects.get(name=self.cleaned_data.get("graduation"))
university.set_graduation = graduation
university.set_creator = user
university.set_updator = user
university.save()
return university
This is my university view.py to create a university
def create_university(request):
if request.method == 'POST':
user = get_user(request)
logo = request.FILES.get('logo')
image = request.FILES.get('image')
auto_id = int(request.POST.get('id'))
title = request.POST.get('title')
graduation = "berlin"
location = request.POST.get('location')
location_url = request.POST.get('location_url')
established = request.POST.get('established')
ranking = request.POST.get('ranking')
intake = request.POST.get('intake')
acceptance_rate = request.POST.get('acceptance')
teacher_ratio = request.POST.get('teacher')
about_university = request.POST.get('about')
description = request.POST.get('description')
data = {
'user': user,
'title': title,
'id': auto_id,
'location': location,
'location_url': location_url,
'estd': established,
'ranking': ranking,
'intake': intake,
'acceptance_rate': acceptance_rate,
'teacher_ratio': teacher_ratio,
'about_university': about_university,
'description': description,
'logo': logo,
'image': image,
'graduation': graduation}
print(data)
create_university_form = CreateUniversityForm(data=data)
if create_university_form.is_valid():
university = create_university_form.save()
context = {
'title': university.title
}
return JsonResponse(context)
else:
context = {
"validationerror": "validation error"
}
return JsonResponse(context)
university model admin view
All i wanted to do is to create a new univerisity object but this auto_id is killing me, also i cant understand this BaseModel system
File "C:\Users\abinp\Documents\projects\tegain\venv\lib\site-packages\django\db\backends\utils.py", line 89, in _execute
return self.cursor.execute(sql, params)
django.db.utils.IntegrityError: null value in column "auto_id" of relation "university_university" violates not-null constraint
DETAIL: Failing row contains (c496cf2f-2966-49f3-b2d4-9efa4f3323b4, null, 2022-08-08 10:36:59.869385+00, 2022-08-08 10:36:59.869385+00, f, null, null, null, null, null, null, null, null, null, null, , , null, null).
As the error says, you have a null value in the ID column.
auto_id = models.PositiveIntegerField(db_index=True, unique=True)
You have PositiveIntegerField, that means that you have to fill it and you're probably not doing that in forms. For ID you should always use AutoField.
So it returns null because there is nothing in your auto_id variable. I think replace this with AutoField should solve the problem.
Documentation search for AutoField:
https://docs.djangoproject.com/en/4.1/ref/models/fields/

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.

Foreign Key Error to Itself on Django

So I am trying to create an inline set similar to this image (http://oi48.tinypic.com/4gm5w2.jpg) so I can add multiple prices for different sizes for a product. I can't get it to even display the area in the django admin. On top of that by doing so I get the error:
<class 'apps.main.admin.PriceInline'>: (admin.E202) 'main.Apparel_Price' has no ForeignKey to 'main.Apparel_Price'.
models.py:
#python_2_unicode_compatible
class Apparel_Product(models.Model):
product_name = models.CharField(_("Name"), max_length=255)
default='media/None/no-img.jpg')
product_gender_type = models.CharField(max_length=256, choices=[('male', 'Male'), ('female', 'Female'), ('unisex', 'Unisex')])
product_brand = models.CharField(_("Brand"),max_length=25)
product_sizes = models.CharField(_("Sizes"),max_length=25)
product_colors = models.CharField(_("Colors"),max_length=25)
product_price = models.CharField(_("Price"),max_length=10)
product_description = models.CharField(_("Description"),max_length=500)
product_shipping_options = models.CharField(_("Shipping Options"),max_length=250)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
verbose_name = _("Apparel Product")
verbose_name_plural = _("Apparel Products")
def __str__(self):
return self.album_name
#python_2_unicode_compatible
class Apparel_Picture(models.Model):
master_apparel_product = models.ForeignKey(Apparel_Product, verbose_name=_("Apparel Product"), on_delete=models.CASCADE)
product_caption = models.CharField(_("Caption"), max_length=255)
product_photo = models.ImageField(_("Picture"), upload_to='media/')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
verbose_name = _("Picture")
verbose_name_plural = _("Pictures")
def __str__(self):
return self.photo_caption
#python_2_unicode_compatible
class Apparel_Price(models.Model):
# master_apparel_product = models.ForeignKey(Apparel_Product, verbose_name=_("Apparel Product"), on_delete=models.CASCADE)
master_apparel_product = models.OneToOneField(Apparel_Product, verbose_name=_("Apparel Product"), on_delete=models.CASCADE)
product_price = models.CharField(_("Price"), max_length=255)
product_size = models.ForeignKey(Apparel_Product, verbose_name=_("Apparel Product"), on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
verbose_name = _("Price")
verbose_name_plural = _("Prices")
def __str__(self):
return self.product_price
admin.py:
from django.contrib import admin
from .models import Apparel_Product, Apparel_Picture, Apparel_Price
# Register your models here.
def get_picture_preview(obj):
if obj.pk: # if object has already been saved and has a primary key, show picture preview
return """<img src="{src}" alt="{title}" style="max-width: 200px; max-height: 200px;" />""".format(
src=obj.photo.url,
title=obj.photo_caption,
)
return ("(choose a picture and save and continue editing to see the preview)")
get_picture_preview.allow_tags = True
get_picture_preview.short_description = ("Picture Preview")
class PictureInline(admin.StackedInline):
model = Apparel_Picture
extra = 0
fields = ["get_edit_link", "product_caption", "product_photo", get_picture_preview]
readonly_fields = ["get_edit_link", get_picture_preview]
def get_edit_link(self, obj=None):
if obj.pk: # if object has already been saved and has a primary key, show link to it
url = reverse('admin:%s_%s_change' % (obj._meta.app_label, obj._meta.model_name), args=[force_text(obj.pk)])
return """{text}""".format(
url=url,
text=_("Edit this %s separately") % obj._meta.verbose_name,
)
return ("(save and continue editing to create a link)")
get_edit_link.short_description = ("Edit link")
get_edit_link.allow_tags = True
class PriceInline(admin.TabularInline):
model = Apparel_Price
extra = 0
fields = ["price",]
#admin.register(Apparel_Product)
class Apparel_ProductAdmin(admin.ModelAdmin):
save_on_top = True
fields = ["product_name", "product_gender_type", "product_brand", "product_sizes", "product_colors", "product_price", "product_description", "product_shipping_options",]
inlines = [PictureInline]
#admin.register(Apparel_Picture)
class Apparel_PictureAdmin(admin.ModelAdmin):
save_on_top = True
fields = ["master_apparel_product", "product_caption", "product_photo", get_picture_preview]
readonly_fields = [get_picture_preview]
#admin.register(Apparel_Price)
class Apparel_PriceAdmin(admin.ModelAdmin):
save_on_top = True
fields = ["master_apparel_product", "product_price",]
inlines = [PriceInline,]
So I am really confused how main.Apparel_Price would need a foreign key to itself. The one for the picture works but the one for the prices do not and I tried copying them and it didn't work. Help would greatly be appreciated.
PriceInline has model Apparel_Price same as Apparel_PriceAdmin. Just use PriceInline as inline in Apparel_ProductAdmin.

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