I'm trying to make app with Many-To-Many Field. And I write it and wont to try it. So, I started shell and make some objects and I get this error.
>>> mzz.controlsOrganization.add(org1, org2)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/fdobrovolny/virtualenv/first/lib/python2.7/site-packages/django/db/models/fields/related.py", line 848, in __get__
through=self.field.rel.through,
File "/home/fdobrovolny/virtualenv/first/lib/python2.7/site-packages/django/db/models/fields/related.py", line 538, in __init__
(instance, source_field_name))
ValueError: "<MZZ: TEST 1>" needs to have a value for field "mzz" before this many-to-many relationship can be used.
MZZ class:
class MZZ(models.Model):
name = models.CharField(max_length=100)
name.short_decription = u'Název MZZ'
ident = models.CharField(max_length=45, unique=True)
active = models.BooleanField()
active.boolean = True
kind = models.ForeignKey(kind)
deliveryDate = models.DateField()
stateAfterDelivery = models.CharField(max_length=200)
dateOfCommissioning = models.DateField()
prescribedParameters = models.CharField(max_length=200)
responsibleStaff = models.ForeignKey(User)
dateOfManufacture = models.DateField()
manufacturer = models.ForeignKey(organization, related_name='manufacturer')
type = models.CharField(max_length=50)
serialNumber = models.CharField(max_length=80)
frequencyOfControls = models.ForeignKey(controls_frequency)
location = models.CharField(max_length=50)
methodOfControls = models.CharField(max_length=100)
controlsOrganization = models.ManyToManyField(organization, related_name='controlsOrganization')
servisOrganization = models.ManyToManyField(organization, related_name='servisOrganization')
def __unicode__(self):
return self.name'
organization class:
class organization(models.Model):
name = models.CharField(max_length=200)
adress = models.CharField(max_length=200)
telephoneNumber = models.CharField(max_length=35)
email = models.EmailField()
def __unicode__(self):
return self.name
Can please somebody help me?
You have to create the MZZ object and save() it first and then add an organization.
mzz = MZZ() # create
mzz.save() # save()
o = organization()
o.save()
m.organization.add(o) # add(o)
https://docs.djangoproject.com/en/dev/topics/db/examples/many_to_many/
Related
Please help me to find a solution to this error, whene using django-import-export
here is my code :
Models :
class ChartOfAccounts(models.Model):
code = models.CharField('code plan comptable', max_length=20, unique=True)
name = models.CharField('plan comptable', max_length=100)
def __str__(self):
return self.code
class Company(models.Model):
code = models.CharField('code société', max_length=20, unique=True)
name = models.CharField('société', max_length=100)
addr = models.CharField('adresse', max_length=100, blank=True, null=True)
chart_of_accounts = models.ForeignKey(ChartOfAccounts, on_delete=models.CASCADE, verbose_name='code plan comptable')
def __str__(self):
return self.code
class GLAccount(models.Model):
class Meta:
unique_together = (('code', 'chart_of_accounts'),)
code = models.CharField('code compte comptable', max_length=10)
chart_of_accounts = models.ForeignKey(ChartOfAccounts, on_delete=models.CASCADE, verbose_name='code plan comptable')
name = models.CharField('compte comptable', max_length=100, help_text='text descriptif du compte comptable')
def __str__(self):
return f'{self.code}, {self.chart_of_accounts}'
class CompanyAccount(models.Model):
company = models.ForeignKey(Company, verbose_name='code société', on_delete=models.CASCADE)
gl_account = models.ForeignKey(GLAccount, verbose_name='compte comptable', on_delete=models.CASCADE)
Resources :
class CompanyAccountResource(ModelResource):
class Meta:
model = models.CompanyAccount
fields = ('company', 'gl_account',)
exclude = ('id',)
import_id_fields = ('company', 'gl_account',)
skip_unchanged = False
report_skipped = False
# fields
company = Field(
column_name=Meta.model._meta.get_field('company').verbose_name,
attribute='company',
widget=ForeignKeyWidget(models.Company, field='code')
)
gl_account = Field(
column_name=Meta.model._meta.get_field('gl_account').verbose_name,
attribute='gl_account',
widget=ForeignKeyWidget(models.GLAccount, field='code')
)
def get_export_order(self):
export_fields = ['company', 'gl_account', ]
return export_fields
My data is :
Company model data here
ChatOfAccounts model data here
GLAccount model data here
CompanyAccountResource Excel canvas to import data
the problem :
a GLAccount code may apear in 2 chart of accounts, each related to one company, and when try to import data from excel to CompanyAccountResource, the error below will apear :
Line number: 1 - get() returned more than one GLAccount -- it returned 2!
S001, 600000
Traceback (most recent call last):
File "C:\Users\Leo\PycharmProjects\Django\DjangoSnippets\venv\lib\site-packages\import_export\resources.py", line 639, in import_row
instance, new = self.get_or_init_instance(instance_loader, row)
File "C:\Users\Leo\PycharmProjects\Django\DjangoSnippets\venv\lib\site-packages\import_export\resources.py", line 334, in get_or_init_instance
instance = self.get_instance(instance_loader, row)
File "C:\Users\Leo\PycharmProjects\Django\DjangoSnippets\venv\lib\site-packages\import_export\resources.py", line 327, in get_instance
return instance_loader.get_instance(row)
File "C:\Users\Leo\PycharmProjects\Django\DjangoSnippets\venv\lib\site-packages\import_export\instance_loaders.py", line 29, in get_instance
params[field.attribute] = field.clean(row)
File "C:\Users\Leo\PycharmProjects\Django\DjangoSnippets\venv\lib\site-packages\import_export\fields.py", line 66, in clean
value = self.widget.clean(value, row=data)
File "C:\Users\Leo\PycharmProjects\Django\DjangoSnippets\venv\lib\site-packages\import_export\widgets.py", line 396, in clean
return self.get_queryset(value, row, *args, **kwargs).get(**{self.field: val})
File "C:\Users\Leo\PycharmProjects\Django\DjangoSnippets\venv\lib\site-packages\django\db\models\query.py", line 433, in get
raise self.model.MultipleObjectsReturned(
app1.models.GLAccount.MultipleObjectsReturned: get() returned more than one GLAccount -- it returned 2!
The error is occurring because you are defining import_id_fields which don't uniquely identify an object.
import_id_fields is used by the import workflow to identify an existing model instance for update. In your case, the combination of 'company', 'gl_account' is identifying multiple rows in the CompanyAccountResource.
If you need your import logic to update existing instances, then you will have to find a way to uniquely identify the row for update.
I am trying to create manytomany fields in one of the class, I am getting an error "The value of 'list_display[5]' must not be a ManyToManyField"
Need Help, Thanks in advance :)
class ShiftConfig(models.Model):
description = models.CharField(max_length=30)
start_time = models.TimeField()
end_time = models.TimeField()
def __str__(self):
return str(self.id) + ' : ' + str(self.start_time)
class FaultConfig(models.Model):
description = models.CharField(max_length=30)
message = models.ForeignKey(Message, null=True, on_delete=models.SET_NULL)
recipients = models.ForeignKey(UserGroup, null=True, on_delete=models.SET_NULL)
alert_time = models.DurationField(default=timedelta(0.0001))
repeat = models.PositiveSmallIntegerField()
escalated_fault = models.ForeignKey('self', null=True, on_delete=models.SET_NULL, blank=True)
def __str__(self):
return str(self.id) + ' : ' + str(self.description)
Here is the concerned class.
class WorkStation(models.Model):
name = models.CharField(max_length=30)
location = models.CharField(max_length=30)
department= models.ForeignKey(Department, null=True, on_delete=models.SET_NULL)
current_user=models.ForeignKey(User, null=True, on_delete=models.SET_NULL)
allowed_fault_configs = models.ManyToManyField(FaultConfig, through='WFMembership', through_fields=('workstation', 'fault_config'))
allowed_shift_configs = models.ManyToManyField(ShiftConfig, through='WSMembership', through_fields=('workstation', 'shift_config'))
def __str__(self):
return str(self.id) + ' : ' + str(self.name)
class WFMembership(models.Model):
workstation = models.ForeignKey(WorkStation, on_delete=models.CASCADE)
fault_config = models.ForeignKey(FaultConfig, on_delete=models.CASCADE)
class WSMembership(models.Model):
workstation = models.ForeignKey(WorkStation, on_delete=models.CASCADE)
shift_config = models.ForeignKey(ShiftConfig, on_delete=models.CASCADE)
Here is the error which mentions that the field must not be ManyToManyField
Watching for file changes with StatReloader
Performing system checks...
Exception in thread django-main-thread:
Traceback (most recent call last):
File "C:\Program Files\Python36\lib\threading.py", line 916, in _bootstrap_inner
self.run()
File "C:\Program Files\Python36\lib\threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "C:\Program Files\Python36\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper
fn(*args, **kwargs)
File "C:\Program Files\Python36\lib\site-packages\channels\management\commands\runserver.py", line 69, in inner_run
self.check(display_num_errors=True)
File "C:\Program Files\Python36\lib\site-packages\django\core\management\base.py", line 441, in check
raise SystemCheckError(msg)
django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues:
ERRORS:
<class 'andon.admin.WorkStation'>: (admin.E109) The value of 'list_display[5]' must not be a ManyToManyField.
<class 'andon.admin.WorkStation'>: (admin.E109) The value of 'list_display[6]' must not be a ManyToManyField.
System check identified 2 issues (0 silenced).
Here is the admin.py for Workstation
#admin.register(WorkStation)
class WorkStation(admin.ModelAdmin):
list_display = ('id', 'name','location','department','current_user','allowed_fault_configs', 'allowed_shift_configs')
list_display_links = ('id', 'name')
Can you post your admin.py? Specifically andon.admin.WorkStation?
Please refer to Django documentation for ManytoManyField usage in admin console.
You can write a custom function to retrieve those values from the ManyToManyField.
I am having problems running my server after I try to integrate the database with the application using the "python manage.py inspectdb > /models.py" command.
This is what I have in my models.py file
# This is an auto-generated Django model module.
# You'll have to do the following manually to clean this up:
# * Rearrange models' order
# * Make sure each model has one field with primary_key=True
# Feel free to rename the models, but don't rename db_table values or field names.
#
# Also note: You'll have to insert the output of 'django-admin.py sqlcustom [appname]'
# into your database.
from __future__ import unicode_literals
from django.db import models
class AuthGroup(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=80)
class Meta:
db_table = 'auth_group'
class AuthGroupPermissions(models.Model):
id = models.IntegerField(primary_key=True)
group = models.ForeignKey(AuthGroup)
permission = models.ForeignKey('AuthPermission')
class Meta:
db_table = 'auth_group_permissions'
class AuthPermission(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=50)
content_type = models.ForeignKey('DjangoContentType')
codename = models.CharField(max_length=100)
class Meta:
db_table = 'auth_permission'
class AuthUser(models.Model):
id = models.IntegerField(primary_key=True)
password = models.CharField(max_length=128)
last_login = models.DateTimeField()
is_superuser = models.BooleanField()
username = models.CharField(max_length=30)
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
email = models.CharField(max_length=75)
is_staff = models.BooleanField()
is_active = models.BooleanField()
date_joined = models.DateTimeField()
class Meta:
db_table = 'auth_user'
class AuthUserGroups(models.Model):
id = models.IntegerField(primary_key=True)
user = models.ForeignKey(AuthUser)
group = models.ForeignKey(AuthGroup)
class Meta:
db_table = 'auth_user_groups'
class AuthUserUserPermissions(models.Model):
id = models.IntegerField(primary_key=True)
user = models.ForeignKey(AuthUser)
permission = models.ForeignKey(AuthPermission)
class Meta:
db_table = 'auth_user_user_permissions'
class DjangoContentType(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=100)
app_label = models.CharField(max_length=100)
model = models.CharField(max_length=100)
class Meta:
db_table = 'django_content_type'
class DjangoSession(models.Model):
session_key = models.CharField(max_length=40)
session_data = models.TextField()
expire_date = models.DateTimeField()
class Meta:
db_table = 'django_session'
class DjangoSite(models.Model):
id = models.IntegerField(primary_key=True)
domain = models.CharField(max_length=100)
name = models.CharField(max_length=50)
class Meta:
db_table = 'django_site'
class DjangoUser(models.Model):
firstname = models.CharField(max_length=256)
lastname = models.CharField(max_length=256)
username = models.CharField(primary_key=True, max_length=256)
password = models.CharField(max_length=256)
class Meta:
db_table = 'django_user'
and this is the error message I get
Unhandled exception in thread started by <bound method Command.inner_run of <django.contrib.staticfiles.management.comma
nds.runserver.Command object at 0x0000000002CD1518>>
Traceback (most recent call last):
File "C:\Python33\lib\site-packages\django\core\management\commands\runserver.py", line 92, in inner_run
self.validate(display_num_errors=True)
File "C:\Python33\lib\site-packages\django\core\management\base.py", line 280, in validate
num_errors = get_validation_errors(s, app)
File "C:\Python33\lib\site-packages\django\core\management\validation.py", line 35, in get_validation_errors
for (app_name, error) in get_app_errors().items():
File "C:\Python33\lib\site-packages\django\db\models\loading.py", line 166, in get_app_errors
self._populate()
File "C:\Python33\lib\site-packages\django\db\models\loading.py", line 72, in _populate
self.load_app(app_name, True)
File "C:\Python33\lib\site-packages\django\db\models\loading.py", line 96, in load_app
models = import_module('.models', app_name)
File "C:\Python33\lib\site-packages\django\utils\importlib.py", line 35, in import_module
__import__(name)
TypeError: source code string cannot contain null bytes
It seems I have a null variable some place but I don't know where that is coming from. I would appreciate some help.
I just had this problem myself. I finally fixed it:
open the generated model.py file in Notepad++ (or other)
copy/paste the generated code into a new file in IDLE
Save over model.py
I'm not sure why this works, but I got an encoding error trying to open the file directly in IDLE. So I copy/pasted the code, and it fixes everything.
I had the same problem using Sublime 3 as editor. It got solved if I resaved the models.py file in my app folder as 'Save with Encoding :: UTF-8'.
I am using the following models for my first django site. But I am currently having problems with how to access the wishes of a user.
class Group(models.Model):
title = models.CharField(max_length=100)
users = models.ManyToManyField(User, related_name='group_users')
description = models.TextField()
added = models.DateTimeField()
owner = models.ForeignKey(User)
def __unicode__(self):
return self.title
class Wish(models.Model):
name = models.CharField(max_length=50)
user = models.ForeignKey(User, related_name='wish_user')
bought = models.IntegerField(default=0)
bought_by = models.ForeignKey(User, related_name='wish_buyer')
added_by = models.ForeignKey(User, related_name='wish_adder')
cost = models.FloatField()
added = models.DateTimeField()
def __unicode__(self):
return self.name
def is_bought(self):
return self.bought % 2 == 1
def is_editable(self):
return self.added >= timezone.now() - datetime.timedelta(hours=1)
When I go to the django shell I get the following:
$ ./manage.py shell
>>> from django.contrib.auth.models import User
>>> from wish.models import Wish, Group
>>> user1 = User.objects.filter(id=1)[0]
>>> user1.group_set.all()
[]
>>> user1.wish_set.all()
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: 'User' object has no attribute 'wish_set'
>>>
Why doesn't the User object get the wish_set like it does get the group_set ?
That's because you renamed them to wish_user, wish_buyer and wish_adder. Whereas for the group you have wish_set implicity from the owner property and the explicit group_users.
The related_name parameter tells Django how to name the reverse relation. If it's not given it will be <field name>_set
Is it possible to have a field in a Django model which does not get stored in the database.
For example:
class Book(models.Model):
title = models.CharField(max_length=75)
description models.CharField(max_length=255, blank=True)
pages = models.IntegerField()
none_db_field = ????
I could then do
book = Book.objects.get(pk=1)
book.none_db_field = 'some text...'
print book.none_db_field
Thanks
As long as you do not want the property to persist, I don't see why you can't create a property like you described. I actually do the same thing on certain models to determine which are editable.
class Email(EntryObj):
ts = models.DateTimeField(auto_now_add=True)
body = models.TextField(blank=True)
user = models.ForeignKey(User, blank=True, null=True)
editable = False
...
class Note(EntryObj):
ts = models.DateTimeField(auto_now_add=True)
note = models.TextField(blank=True)
user = models.ForeignKey(User, blank=True, null=True)
editable = True
Creating a property on the model will do this, but you won't be able to query on it.
Example:
from django.db import models
class Person(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
def _get_full_name(self):
return "%s %s" % (self.first_name, self.last_name)
def _set_full_name(self, combined_name):
self.first_name, self.last_name = combined_name.split(' ', 1)
full_name = property(_get_full_name)
full_name_2 = property(_get_full_name, _set_full_name)
Usage:
from mysite.models import Person
a = Person(first_name='John', last_name='Lennon')
a.save()
a.full_name
'John Lennon'
# The "full_name" property hasn't provided a "set" method.
a.full_name = 'Paul McCartney'
Traceback (most recent call last):
...
AttributeError: can't set attribute
# But "full_name_2" has, and it can be used to initialise the class.
a2 = Person(full_name_2 = 'Paul McCartney')
a2.save()
a2.first_name
'Paul'
To make it an instance variable (so each instance gets its own copy), you'll want to do this
class Book(models.Model):
title = models.CharField(max_length=75)
#etc
def __init__(self, *args, **kwargs):
super(Foo, self).__init__(*args, **kwargs)
self.editable = False
Each Book will now have an editable that wont be persisted to the database
If you want i18n support:
# Created by BaiJiFeiLong#gmail.com at 2022/5/2
from typing import Optional
from django.db import models
from django.utils.translation import gettext_lazy as _
class Blog(models.Model):
title = models.CharField(max_length=128, unique=True, verbose_name=_("Title"))
content = models.TextField(verbose_name=_("Content"))
_visitors: Optional[int] = None
#property
def visitors(self):
return self._visitors
#visitors.setter
def visitors(self, value):
self._visitors = value
visitors.fget.short_description = _("Visitors")