Django save_m2m() and excluded field - django

UPDATE: I ended up creating a new forms.Form instead of using a ModelForm
In a ModelForm, I replaced a field by excluding it and adding a new one
with the same name, as shown below in AddRestaurantForm. When saving
the form with the code shown below, I get an error in form.save_m2m()
("Truncated incorrect DOUBLE value"), which seems to be due to the
function to attempt to save the tag field, while it is excluded.
Is the save_m2m() function supposed to save excluded fields?
Is there anything wrong in my code?
Thanks
Jul
(...)
new_restaurant = form.save(commit=False)
new_restaurant.city = city
new_restaurant.save()
tags = form.cleaned_data['tag']
if(tags!=''): tags=tags.split(',')
for t in tags:
tag, created = Tag.objects.get_or_create(name = t.strip())
tag.save()
new_restaurant.tag.add(tag)
new_restaurant.save()
form.save_m2m()
models.py
class Tag(models.Model):
name = models.CharField(max_length=100, unique=True)
class Restaurant(models.Model):
name = models.CharField(max_length=50)
city=models.ForeignKey(City)
category=models.ManyToManyField(Category)
tag=models.ManyToManyField(Tag, blank=True, null=True)
forms.py
class AddRestaurantForm(ModelForm):
name = forms.CharField(widget=forms.TextInput(attrs=classtext))
city = forms.CharField(widget=forms.TextInput(attrs=classtext), max_length=100)
tag = forms.CharField(widget=forms.TextInput(attrs=classtext), required=False)
class Meta:
model = Restaurant
exclude = ('city','tag')
Traceback:
File "/var/lib/python-support/python2.5/django/core/handlers/base.py"
in get_response
92. response = callback(request, *callback_args,
**callback_kwargs) File "/home/jul/atable/../atable/resto/views.py" in addRestaurant
498. form.save_m2m() File "/var/lib/python-support/python2.5/django/forms/models.py" in
save_m2m
75. f.save_form_data(instance, cleaned_data[f.name]) File "/var/lib/python-support/python2.5/django/db/models/fields/
related.py" in save_form_data
967. setattr(instance, self.attname, data) File "/var/lib/python-support/python2.5/django/db/models/fields/
related.py" in set
627. manager.add(*value) File "/var/lib/python-support/python2.5/django/db/models/fields/
related.py" in add
430. self._add_items(self.source_col_name, self.target_col_name, *objs) File
"/var/lib/python-support/python2.5/django/db/models/fields/
related.py" in _add_items
497. [self._pk_val] + list(new_ids)) File "/var/lib/python-support/python2.5/django/db/backends/util.py" in
execute
19. return self.cursor.execute(sql, params) File "/var/lib/python-support/python2.5/django/db/backends/mysql/
base.py" in execute
84. return self.cursor.execute(query, args) File "/var/lib/python-support/python2.5/MySQLdb/cursors.py" in execute
168. if not self._defer_warnings: self._warning_check() File "/var/lib/python-support/python2.5/MySQLdb/cursors.py" in
_warning_check
82. warn(w[-1], self.Warning, 3) File "/usr/lib/python2.5/warnings.py" in warn
62. globals) File "/usr/lib/python2.5/warnings.py" in warn_explicit
102. raise message
Exception Type: Warning at /restaurant/add/ Exception Value:
Truncated incorrect DOUBLE value: 'a'

I see you also posted this same question to Django-users. I'll copy the answer I've posted there:
Firstly, it is no use just giving the name of the error. Errors come
with tracebacks, for good reason: they allow us to see exactly where
the error is occurring, and the context.
Anyway, in your case, there doesn't seem to be any need to use
save_m2m. The documentation states:
"Calling save_m2m() is only required if you use save(commit=False)"
In your case, you've already saved the form to get the new_restaurant
instance, and you're adding tags to that instance with no problem. The
last two calls, to new_restaurant.save() and form.save_m2m(), are unnecessary.

You don't need either of the last two "save" calls. Your tags relation will be implicitly saved by virtue of the add(). I'd just drop those from the code.

Related

JobPost' object has no attribute 'job_type'

I have simple view to create custom jobs and post them on a job_portal, but I am getting the below-mentioned error, I am working with many-to-many fields and have gone through the docs, set method is not working it seems, I have posted the trace as well, but its pointing to the strange error, foreign that it is mentioning is already set to null, thanks in advance
def create_job(request):
company_ = Company.objects.values_list('name', flat=True)
if request.method == 'POST':
# getting company by name for reference
job_title = request.POST['job_title']
company_name = request.POST['company_name']
company = get_object_or_404(Company, name__iexact=company_name)
address = request.POST.get('street_addr')
city = request.POST['city']
state = request.POST['state']
country = request.POST['country']
zip_ = request.POST.get('zip_code')
skill_names = request.POST.getlist('skill_name')
start_salary = request.POST.get('salary_start')
end_salary = request.POST.get('salary_end')
# create job skills if not already present inside DB
print(skill_names)
skill_list = []
for skill in skill_names:
skill_nam, created = Skillset.objects.get_or_create(skill_name__iexact=skill,defaults={
'skill_name' : skill
})
skill_list.append(skill_nam)
job_loc = JobLocation(address=address, city=city,
state=state, country=country, zip_code=zip_)
job_loc.save()
job_descrip = request.POST['job_descrip']
job_skill_ = request.POST.getlist('job_skill_level')
job_pst = JobPost(title=job_title,
cmpny_name=company, job_description=job_descrip, salary_start=start_salary,salary_end=end_salary)
job_pst.job_posters.set(request.user) <--- i am getting error here
job_pst.save()
#skill_list has skill names
job_skill_set = []
for job_skill_name, job_level in zip(skill_list, job_skill_):
skil_set = Skillset.objects.filter(skill_name=job_skill_name)
job_skillset = Job_Skillset(job_post=job_pst, skill_level=job_level)
job_skillset.skill.set(skil_set)
job_skill_set.append(job_skillset)
Job_Skillset.objects.bulk_create(job_skill_set)
messages.add_message(request,messages.SUCCESS,'Job post successfully submitted!')
return redirect('/dashboard/')
return render(request, 'company/company_entry.html', context={
'contxt': 'job_contxt',
'company': company_,
# 'skills_req': job_skill,
})
Trace
Traceback (most recent call last):
File "C:\Users\atifs\Documents\job_portal\jobportal-env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\atifs\Documents\job_portal\jobportal-env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\atifs\Documents\job_portal\jobportal\job_management\views.py", line 60, in create_job
job_pst.job_posters.set(request.user)
File "C:\Users\atifs\Documents\job_portal\jobportal-env\lib\site-packages\django\db\models\fields\related_descriptors.py", line 536, in __get__
return self.related_manager_cls(instance)
File "C:\Users\atifs\Documents\job_portal\jobportal-env\lib\site-packages\django\db\models\fields\related_descriptors.py", line 851, in __init__
raise ValueError('"%r" needs to have a value for field "%s" before '
File "C:\Users\atifs\Documents\job_portal\jobportal-env\lib\site-packages\django\db\models\base.py", line 521, in __repr__
return '<%s: %s>' % (self.__class__.__name__, self)
File "C:\Users\atifs\Documents\job_portal\jobportal\job_management\models.py", line 24, in __str__
return str(self.job_type)
Exception Type: AttributeError at /create_job/
Exception Value: 'JobPost' object has no attribute 'job_type'
Your error is located here:
File "C:\Users\atifs\Documents\job_portal\jobportal\job_management\models.py", line 24, in __str__
return str(self.job_type)
so, I guess the JobPost model has the method def __str__() that you're overriding, and it has a mistake in using a non-existing attribute called job_type.
Take a look at this method first.
My own code style warning: use black to auto-format your code, it will look much more readable!🙌

Django 1.9.5: FieldError for reverse lookup fields occasionally

I'm getting a frustrating intermittent error in Django, when attempting to run the objects.all() for a Queryset that is prefetching. There is an issue where occasionally the model._meta seems to be missing fields, between instantiation of a queryset and running an iteration through it. It's almost as if the queryset's prefetch doesn't actually get run in time for the iteration of the list of objects.
In this example, data.service_log is simply a queryset with some prefetched items called servicelog. When I run the queryset in the shell, I can look at all the fields in the self.names_to_path(lookup_splitted, self.get_meta()) method on the queryset. They are all there, specifically the "servicelog."
Notice this Traceback for this error it says that "servicelog" is not an available field, yet it lists it in the list of fields to choose from. This seems to be a Django bug, but I can't be sure because I can't explain or isolate the behavior. I can't possibly be the only person getting this error. It seems to be in django/db/models/sql/query.py in the names_to_paths() method. Here's the code that is failing to resolve:
query.py names_to_paths():
field = None
try:
field = opts.get_field(name)
except FieldDoesNotExist:
if name in self.annotation_select:
field = self.annotation_select[name].output_field
if field is not None:
# Fields that contain one-to-many relations with a generic
# model (like a GenericForeignKey) cannot generate reverse
# relations and therefore cannot be used for reverse querying.
if field.is_relation and not field.related_model:
raise FieldError(
"Field %r does not generate an automatic reverse "
"relation and therefore cannot be used for reverse "
"querying. If it is a GenericForeignKey, consider "
"adding a GenericRelation." % name
)
try:
model = field.model._meta.concrete_model
except AttributeError:
model = None
else:
# We didn't find the current field, so move position back
# one step.
pos -= 1
if pos == -1 or fail_on_missing:
field_names = list(get_field_names_from_opts(opts))
available = sorted(field_names + list(self.annotation_select))
raise FieldError("Cannot resolve keyword %r into field. "
"Choices are: %s" % (name, ", .join(available)))
break
field does not get set in the first try, then the condition statementif field is not Nonefails so we enter theelseblock. There theposgets reduced by one, but since this field is 'servicelog' it is already at 0. However, when I try this in the shell, it always finds thefieldwithopts.get_field('servicelog')`. Only when run from WSGI and Apache2 does this failure occur. Again, it isn't all the time, which makes it extremely difficult to test. I'm perplexed by this, and am not sure where to look for clues. PLEASE if anybody has ANY ideas of what to explore, I'd be so appreciative.
Traceback (most recent call last):
File "/var/www/fast/services/views/edit.py", line 12897, in service_log
for service in data.service_log:
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 258, in __iter__
self._fetch_all()
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 1076, in _fetch_all
self._prefetch_related_objects()
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 656, in _prefetch_related_objects
prefetch_related_objects(self._result_cache, self._prefetch_related_lookups)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 1457, in prefetch_related_objects
obj_list, additional_lookups = prefetch_one_level(obj_list, prefetcher, lookup, level)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 1556, in prefetch_one_level
prefetcher.get_prefetch_queryset(instances, lookup.get_current_queryset(level)))
File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/related_descriptors.py", line 802, in get_prefetch_queryset
queryset = queryset._next_is_sticky().filter(**query)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 790, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 808, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/query.py", line 1243, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/query.py", line 1269, in _add_q
allow_joins=allow_joins, split_subq=split_subq,
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/query.py", line 1149, in build_filter
lookups, parts, reffed_expression = self.solve_lookup_type(arg)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/query.py", line 1035, in solve_lookup_type
_, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/query.py", line 1330, in names_to_path
"Choices are: %s" % (name, ", ".join(available)))
FieldError: Cannot resolve keyword u'servicelog' into field. Choices are: additional_county_worker_notes, adoption_disrupted, adoption_first_name, adoption_last_name, adoption_middle_name, adoption_placement_date, adoption_placement_reason, adoption_placement_reason_id, adoption_placement_type, adoption_risk_level, adoption_risk_level_id, adoption_termination_date, adoption_termination_destination, adoption_termination_reason, adoption_termination_reason_id, adoptive_placement, agency, agency_id, all_items_outstanding, all_items_past_due, appeal_process_date, attached_file, attends_college, attorney_email_address, attorney_email_address_id, attorney_fax, attorney_fax_id, attorney_investigator_email_address, attorney_investigator_email_address_id, attorney_investigator_fax, attorney_investigator_fax_id, attorney_investigator_name, attorney_investigator_phone, attorney_investigator_phone_id, attorney_name, attorney_phone, attorney_phone_id, blood_related_to_applicants, blood_relationship, casa_email_address, casa_email_address_id, casa_fax, casa_fax_id, casa_name, casa_phone, casa_phone_id, certification_items_outstanding, certification_items_past_due, classification, classification_id, client, client_id, county_adoption_worker, county_adoption_worker_cell, county_adoption_worker_cell_id, county_adoption_worker_email_address, county_adoption_worker_email_address_id, county_adoption_worker_fax, county_adoption_worker_fax_id, county_adoption_worker_office, county_adoption_worker_office_id, county_adoption_worker_phone, county_adoption_worker_phone_id, county_adoption_worker_title, county_case_number, county_worker, county_worker_cell, county_worker_cell_id, county_worker_email_address, county_worker_email_address_id, county_worker_fax, county_worker_fax_id, county_worker_office, county_worker_office_id, county_worker_phone, county_worker_phone_id, county_worker_title, court, court_case_name, court_case_number, court_department, court_id, created, current_grade, date_identified_adoptive, date_placed_with_home, deleted, discharge_summary, eligibility_worker, eligibility_worker_email_address, eligibility_worker_email_address_id, eligibility_worker_phone, eligibility_worker_phone_id, emergency_placement, employed_80_hours, enable_discharge_summary, expected_type, expected_type_id, extended_family_contact_allowed, final_payment_amount, finalization_date, foreign_placement, hearing_36626_date, homestudy, id, incident_placement_1, incident_placement_2, incident_placement_3, incident_placement_4, individualized_plan_review, inhousemove, interpretive_summary, item_due, items_approved, items_pending, items_rejected, items_update_requested, la_county_id, medi_cal, medi_cal_eligibility_phone, medi_cal_eligibility_phone_id, medi_cal_eligibility_worker, medi_cal_id, modified, monthly_monitored_visit_hours, mother_child, move_in_type, move_out_type, new_protective_custody_petition, non_minor_dependent, non_truant, notes, number_of_files_required, other_school_contact, other_school_contact_first_name, other_school_contact_last_name, parent_payment_override_annually, parent_payment_override_daily, parent_payment_override_monthly, parental_contact_allowed, parental_group, parental_group_id, payment_amount, percent_certified, percent_items_complete, person_number, placement, placement_date, placement_id, placement_payment_override_annually, placement_payment_override_daily, placement_payment_override_monthly, placement_reason, placement_reason_details, placement_reason_id, placement_self, placer_shelter_bed, prior_placement, progress_summary, projected_adoption_36626_date, projected_adoption_finalization_date, projected_adoption_placement_date, recordreview, requires_educational_support, requires_mental_health_services, respite, school, school_different, school_id, school_liaison_email, school_liaison_first_name, school_liaison_last_name, school_liaison_phone, school_liaison_phone_extension, school_notes, serial_number, servicecontact_onbehalf, servicedeliverylog, servicelog, social_worker_at_termination, social_worker_at_termination_id, special_health_care_needs, state_case_number, teachers, termination_date, termination_destination, termination_reason, termination_reason_details, termination_reason_id, therapist, therapy_code, therapy_supervision_requirements, treatment_abilities, treatment_needs, treatment_preferences, treatment_strengths, treatmentneed, update_requested, update_requested_by, update_requested_by_id, update_requested_date, update_requested_note, updateable, use_number_required, uses_psychotropic_medication, visit_frequency_override, visit_frequency_override_id, visitation_restrictions, who_can_pickup_at_home, who_can_pickup_at_school, who_can_visit
UPDATE - adding models/offending view code
models.py
class ParentalGroup(models.Model):
many fields...
class Placement(models.Model):
parental_group = models.ForeignKey(ParentalGroup, null=True, blank=True)
many more fields...
class ServiceLog(models.Model):
parental_group = models.ForeignKey(ParentalGroup, null=True, blank=True)
placement = models.ManyToManyField(Placement, blank=True)
many more fields...
views.py:
data.service_log = ServiceLog.objects.filter(
parental_group=data.pg,
).prefetch_related(
Prefetch(
'placement',
queryset=Placement.objects.all(),
to_attr='placements'
),
)
for service in data.service_log:
some code to generate data to pass to template...
return render_to_response(...)
I had a similar problem using Django 1.8.6 on Gunicorn/Django runserver. I haven't managed to reproduce the error in shell/notebook environment either.
I solved the randomly occurring FieldError by adding related_name to the ManyToManyField. I used a through model in the ManyToManyField though.
In your case:
class ServiceLog(models.Model):
parental_group = models.ForeignKey(ParentalGroup, null=True, blank=True)
placement = models.ManyToManyField(Placement, blank=True, related_name='servicelog')
Jan

Authentication failing for MongoEngineResource with ReferenceField

The request to the embedded field of MongoEngineResource doesn't go through Authentication process, if it contains reference field.
My case is the following:
there is a document Section, which consist of FieldDefinitions
FieldDefinitions are EmbeddedDocuments
FieldDefinition contains embedded_section (optional), which references to the Section, and there is a signal that excludes self-referencing (e.g. embedded_section can only reference to the section, which doesn't contain the FieldDefinition)
this all is a part of moderator's interface, so i use authorization for all kinds of requests (get, post, patch, etc.)
Here is the code:
from tastypie_mongoengine.resources import MongoEngineResource
from tastypie.authentication import ApiKeyAuthentication
from apps.api.auth import CustomAuthorization
class FieldDefinitionResource(MongoEngineResource):
embedded_section = ReferenceField(attribute='embedded_section',
to='myproject.apps.api.resources.SectionResource',
full=True, null=True)
class Meta:
object_class = models.FieldDefinition # mongoengine EmbeddedDocument
authentication = ApiKeyAuthentication()
authorization = CustomAuthorization()
class SectionResource(MongoEngineResource):
fields = EmbeddedListField(attribute='fields',
of='myproject.apps.api.resources.FieldDefinitionResource',
full=True, null=True)
class Meta:
object_class = models.Section # mongoengine Document
authentication = ApiKeyAuthentication()
authorization = CustomAuthorization()
So, when i'm asking for a Section detail (e.g. /api/v1/section/524df40502c8f109b07ed6ae/), everything goes smooth, and fields attr is being displayed correctly in both cases of the presence and absence of embedded_section.
But an attempt to refer to a specific field (e.g. /api/v1/section/524df40502c8f109b07ed6ae/fields/0/) throws an error:
error_message: "'AnonymousUser' object has no attribute 'has_permission'"
has_permission is a method of MongoUser, which inherits from Django auth.User. In the first case described (Section detail) it does go through Authentication and fills request.user with a proper user object, while in the second case (Section field) it skips Authentication stage entirely, going straight to Authorization.
Am i doing something wrong?
Here is a full traceback:
{"error_message": "'AnonymousUser' object has no attribute 'has_permission'", "traceback": "Traceback (most recent call last):
File "/var/www/vhosts/myproject/local/lib/python2.7/site-packages/tastypie/resources.py", line 195, in wrapper
response = callback(request, *args, **kwargs)
File "/var/www/vhosts/myproject/local/lib/python2.7/site-packages/tastypie_mongoengine/resources.py", line 277, in dispatch_subresource
return resource.dispatch(request=request, **kwargs)
File "/vagrant/myproject/myproject/apps/api/resources.py", line 248, in dispatch
super(FieldDefinitionResource, self).dispatch(request_type, request, **kwargs)
File "/var/www/vhosts/myproject/local/lib/python2.7/site-packages/tastypie_mongoengine/resources.py", line 776, in dispatch
self.instance = self._safe_get(bundle, **kwargs)
File "/var/www/vhosts/myproject/local/lib/python2.7/site-packages/tastypie_mongoengine/resources.py", line 768, in _safe_get
return self.parent.cached_obj_get(bundle=bundle, **filters)
File "/var/www/vhosts/myproject/local/lib/python2.7/site-packages/tastypie/resources.py", line 1113, in cached_obj_get
cached_bundle = self.obj_get(bundle=bundle, **kwargs)
File "/var/www/vhosts/myproject/local/lib/python2.7/site-packages/tastypie_mongoengine/resources.py", line 528, in obj_get
return super(MongoEngineResource, self).obj_get(bundle=bundle, **kwargs)
File "/var/www/vhosts/myproject/local/lib/python2.7/site-packages/tastypie/resources.py", line 2069, in obj_get
self.authorized_read_detail(object_list, bundle)
File "/var/www/vhosts/myproject/local/lib/python2.7/site-packages/tastypie/resources.py", line 589, in authorized_read_detail
auth_result = self._meta.authorization.read_detail(object_list, bundle)
File "/vagrant/myproject/myproject/apps/api/auth.py", line 201, in read_detail
bundle.request.user.has_permission('read_detail',
File "/var/www/vhosts/myproject/local/lib/python2.7/site-packages/django/utils/functional.py", line 205, in inner
return func(self._wrapped, *args)
AttributeError: 'AnonymousUser' object has no attribute 'has_permission'
"}
It is a known issue in django-tastypie-mongoengine: see
https://github.com/wlanslovenija/django-tastypie-mongoengine/issues/71
https://github.com/wlanslovenija/django-tastypie-mongoengine/issues/72
and https://github.com/wlanslovenija/django-tastypie-mongoengine/issues/70
Those 3 issues are about the same problem:
The Authentication is being performed only before the action itself, but not before actions on a resource prior to the target action.
Example (using the code in my question): the target action update_detail of the instance of FieldDefinitionResource, which is a child of SectionResource. Prior to updating a detail of FieldDefinitionResource, there is a read_detail of SectionResource - and this is an action, for which django-tastypie-mongoengine skips the Authentication stage. It results in the absence of request.user, which in its turn prevents the work-flow from moving towards the target action (update_detail of the child resource).
This applies for EmbeddedDocumentField, EmbeddedListField, ReferencedListField and ReferenceField.
One possible workaround is to override the authorization for embedded / referenced document:
class CustomAuthorization(Authorization):
def read_detail(self, object_list, bundle):
# Double-check anonymous users, because operations
# on embedded fields do not pass through authentication.
if bundle.request.user.is_anonymous():
MyAuthentication().is_authenticated(bundle.request)
# Now authorize.
try:
return bundle.request.user.has_permission(object_list, 'read_detail')
except AttributeError:
raise Unauthorized(_('You have to authenticate first!'))
But of course, it would be nice to have it solved in the future releases.

ManyToManyField error on production server, fine on dev server

My Django app is raising a puzzling error when using a production served version (via Apache, and Nginx for static), that is not evident for the dev server version on localhost.
I have the models :
class AdaptationLibrary(models.Model):
description = models.CharField( u'Description of adaptation',max_length=400,blank=True,null=True)
name = models.CharField(u'Adaptation Name',max_length=60)
applies_to = models.ManyToManyField(Archetype,related_name =u'archetype_adaptations',null=True,blank=True)
adaptations = jsonfield.JSONField(u'adaptation library items', null=True, blank=True)
def __unicode__(self):
return self.name
and ..
class Archetype(models.Model):
archetype = models.CharField(max_length=20, choices=ARCHETYPE_CHOICES,unique=True)
archetype_family = models.CharField(max_length=60,choices=ARCHETYPE_FAMILY_CHOICES,null=True)
replacement_cost_default = models.FloatField("Default complete asset replacement cost - ($)",null=True, blank=True)
lifespan_default = models.FloatField("Default asset life (yrs)", null=True, blank=True)
age_default = models.FloatField("Default age - (yrs)", null=True, blank=True)
storage_time_default = models.FloatField("Default storage/retention time (hrs)", null=True, blank=True)
def __unicode__(self):
return self.archetype
when I attempt to retrieve related Archetype objects via :
library_archetypes = library_item.applies_to.all()
I get the following error :
FieldError: Cannot resolve keyword u'archetype_adaptations' into field.
Choices are: age_default, archetype, archetype_family, asset, cemlo2, id,
lifespan_default, new_dependency, replacement_cost_default, storage_time_default
Dev and local versions are using the same database, and apart from the call to the AdaptationLibrary ManyToManyField, the rest of the app functions fine.
Can anybody shed some light on this issue?
Cheers
Edit:
As per Rohan's suggestion that it's a migration problem - I've gone the whole box and dice of resetting and re-converting to south. Dev server is still happy - Apache served version throws same errors. Both versions are using the same DB.
(full traceback error) :
ERROR Traceback (most recent call last):
File "C:\Python27\Lib\site-packages\dajaxice\core\DajaxiceRequest.py", line 181, in process
response = '%s' % thefunction(self.request, **argv)
File "C:/Python27/sites/Adaptwater\proto4\ajax.py", line 2636, in populate_adaptation_library
initial_data = dict_to_library_form(library_item_id = library_to_load)
File "C:/Python27/sites/Adaptwater\proto4\ajax.py", line 2556, in dict_to_library_form
library_archetypes = library_item.applies_to.all()
File "C:\Python27\Lib\site-packages\django\db\models\manager.py", line 116, in all
return self.get_query_set()
File "C:\Python27\Lib\site-packages\django\db\models\fields\related.py", line 543, in get_query_set
return super(ManyRelatedManager, self).get_query_set().using(db)._next_is_sticky().filter(**self.core_filters)
File "C:\Python27\Lib\site-packages\django\db\models\query.py", line 621, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "C:\Python27\Lib\site-packages\django\db\models\query.py", line 639, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "C:\Python27\Lib\site-packages\django\db\models\sql\query.py", line 1250, in add_q
can_reuse=used_aliases, force_having=force_having)
File "C:\Python27\Lib\site-packages\django\db\models\sql\query.py", line 1122, in add_filter
process_extras=process_extras)
File "C:\Python27\Lib\site-packages\django\db\models\sql\query.py", line 1316, in setup_joins
"Choices are: %s" % (name, ", ".join(names)))
FieldError: Cannot resolve keyword u'archetype_adaptations' into field. Choices are: age_default, archetype, archetype_family, asset, cemlo2, id, lifespan_default, new_dependency, replacement_cost_default, storage_time_default
Ok - sorry for the self answer, but I fixed the problem, even if I'm still mostly in the dark as to what caused it. After some additional serious googling, I found discussion about the problem in terms of ordering of imports, and model definitions both. For example :
http://chase-seibert.github.com/blog/2010/04/30/django-manytomany-error-cannot-resolve-keyword-xxx-into-a-field.html
After placing the AdaptationLibrary model ahead of Archetype in models.py (and quoting "Archetype" for m2m setup) it appears to be happy. Unless I'm missing something blindingly obvious, this feels like a voodoo fix. Up until now I'd been fastidiously putting referred to models before their referring buddies. But it's a fix nonetheless - so now back to work.
Cheers & Thanks.
Try to use String instead of unicode...sometimes, I have had this problem where Apache is not able to understand UTF-8.

Django model field with default value set violates not null constraint when saved

My field:
signup_date = models.DateTimeField(blank=True,default=datetime.now)
My error when saving:
IntegrityError: null value in column "signup_date" violates not-null constraint
I'm trying to make a simple unit test where I create a bound instance of a ModelForm from a dict and save it.
Thanks.
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/django/signupform/signup/insert_test_data.py", line 27, in <module>
SDF.save()
File "/usr/lib/python2.5/site-packages/Django-1.2.1-py2.5.egg/django/forms/models.py", line 371, in save
fail_message, commit, construct=False)
File "/usr/lib/python2.5/site-packages/Django-1.2.1-py2.5.egg/django/forms/models.py", line 86, in save_instance
instance.save()
File "/usr/lib/python2.5/site-packages/Django-1.2.1-py2.5.egg/django/db/models/base.py", line 435, in save
self.save_base(using=using, force_insert=force_insert, force_update=force_update)
File "/usr/lib/python2.5/site-packages/Django-1.2.1-py2.5.egg/django/db/models/base.py", line 528, in save_base
result = manager._insert(values, return_id=update_pk, using=using)
File "/usr/lib/python2.5/site-packages/Django-1.2.1-py2.5.egg/django/db/models/manager.py", line 195, in _insert
return insert_query(self.model, values, **kwargs)
File "/usr/lib/python2.5/site-packages/Django-1.2.1-py2.5.egg/django/db/models/query.py", line 1479, in insert_query
return query.get_compiler(using=using).execute_sql(return_id)
File "/usr/lib/python2.5/site-packages/Django-1.2.1-py2.5.egg/django/db/models/sql/compiler.py", line 783, in execute_sql
cursor = super(SQLInsertCompiler, self).execute_sql(None)
File "/usr/lib/python2.5/site-packages/Django-1.2.1-py2.5.egg/django/db/models/sql/compiler.py", line 727, in execute_sql
cursor.execute(sql, params)
File "/usr/lib/python2.5/site-packages/Django-1.2.1-py2.5.egg/django/db/backends/util.py", line 15, in execute
return self.cursor.execute(sql, params)
File "/usr/lib/python2.5/site-packages/Django-1.2.1-py2.5.egg/django/db/backends/postgresql_psycopg2/base.py", line 44, in execute
return self.cursor.execute(query, args)
IntegrityError: null value in column "signup_date" violates not-null constraint
from django.db import models
from django.contrib.localflavor.us.models import PhoneNumberField
from datetime import datetime
from models_dropdowns import *
class SignupData(models.Model):
first_name = models.CharField(max_length=128,verbose_name='First Name')
last_name = models.CharField(max_length=128,verbose_name='Last Name')
street1 = models.CharField(max_length=128,verbose_name='Street Address 1')
street2 = models.CharField(max_length=128,verbose_name='Street Address 2')
city = models.CharField(max_length=128)
state = models.CharField(max_length=2)
zip = models.IntegerField(verbose_name='Zip Code')
phone_number = PhoneNumberField(verbose_name='Phone Number XXX-XXX-XXXX')
email = models.EmailField(verbose_name='Email Address')
contact_method = models.ForeignKey('ContactMethodChoice',blank=False,default=-1,verbose_name='Preferred contact method')
birth_date = models.DateField(verbose_name='Birth Date')
policy_number = models.CharField(max_length=128,verbose_name='American Family Auto Insurance Policy Number')
vin = models.CharField(max_length=128,verbose_name='Vehicle Identification Number (VIN)')
vehicle_make = models.ForeignKey('VehicleMakeChoice',verbose_name='VehicleMake')
vehicle_model = models.CharField(max_length=128,verbose_name='Vehicle Model')
vehicle_year = models.ForeignKey('VehicleYearChoice',verbose_name='Vehicle Year')
vehicle_ownership = models.ForeignKey('VehicleOwnershipChoice',blank=False,default=-1,verbose_name='Vehicle Ownership')
vehicle_use = models.ForeignKey('VehicleUseChoice',blank=False,default=-1,verbose_name='Use of Vehicle')
terms_and_conditions = models.BooleanField(verbose_name='I Agree to the terms and conditions. (add link)')
form_user_role = models.ForeignKey('FormUserRoleChoice',blank=False,default=-1,verbose_name='Your Role')
participate_in_feedback = models.BooleanField(verbose_name='<b>Opportunity to provide feedback.</b>...<br><br>',help_text='Please check the box if you would like to participate.')
signup_date = models.DateTimeField(blank=True,default=datetime.now,verbose_name='')
I use the following code to create a bound instance of the form and save it. I run this by importing it from ./manage.py shell.
from signupform.signup.forms import SignupDataForm
keys = ('first_name','last_name','street1','street2','city','state','zip','phone_number','email','contact_method','birth_date','policy_number','vin','vehicle_make','vehicle_model','vehicle_year','vehicle_ownership','vehicle_use','terms_and_conditions','form_user_role','participate_in_feedback')
data = [
('firstname1','lastname1','test1','test1','test1','XX',55555,'555-555-5555','test#asdf.com',1,'01/01/01','####-####-##-##-AAAA-AA','123456789abcdefgh',1,'model',1996,1,1,True,1,True),
('firstname2','lastname2','test2','test2','test2','XX',55555,'555-555-5555','test#asdf.com',1,'01/01/01','####-####-##-##-AAAA-AA','123456789abcdefgh',1,'model',1996,1,1,True,1,True),
('firstname3','lastname3','test3','test3','test3','XX',55555,'555-555-5555','test#asdf.com',1,'01/01/01','####-####-##-##-AAAA-AA','123456789abcdefgh',1,'model',1996,1,1,True,1,True),
('firstname4','lastname4','test4','test4','test4','XX',55555,'555-555-5555','test#asdf.com',1,'01/01/01','####-####-##-##-AAAA-AA','123456789abcdefgh',1,'model',1996,1,1,True,1,True),
]
for d in data:
tmpDict = {}
for i in range(0,len(keys)):
tmpDict[keys[i]] = d[i]
SDF = SignupDataForm(tmpDict)
if not SDF.is_valid():
print SDF.errors
else:
SDF.save()
On problem in you code for me is that you should not write
default=datetime.now()
but instead
default = datetime.now
passing the function as default and not the result of the function at the time the code is parsed. Currently, all your SignupData will have the same signup_date
That said, I am not sure that this is the cause of your bug.
Make sure you're actually using Django to create your objects. Otherwise you're by-passing all the Django magic for setting up default values.
So use something like this:
SignupData.objects.create(blah)
To use your dictionary, use dictionary unpacking:
SignupData.objects.create(**my_dictionary)
BTW, you probably want the default parameter to be a callable, i.e. omit the parens after the now function. This way the function will be called every time a new object is created. With the parens it will only be called once and the same value will be used for all newly created objects.