A quick question about django import-export. Suppose I have a model like the one in the docs, but with some additional constraints (note the Meta class):
class Book(models.Model):
name = models.CharField('Book name', max_length=100)
author = models.ForeignKey(Author, blank=True, null=True)
author_email = models.EmailField('Author email', max_length=75, blank=True)
imported = models.BooleanField(default=False)
published = models.DateField('Published', blank=True, null=True)
price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)
categories = models.ManyToManyField(Category, blank=True)
def __unicode__(self):
return self.name
class Meta:
unique_together = ('name', 'author')
On bulk upload, I would ideally like that any rows containing errors (duplicate entries in this case -- but could be other type of "corrupt" rows too) to be skipped and the rest of the upload to continue. The corrupt rows should be logged into a file containing the row(s) in question and an additional column with the exception name.
There is a generic exceptions.py file :
class ImportExportError(Exception):
"""A generic exception for all others to extend."""
pass
class FieldError(ImportExportError):
"""Raised when a field encounters an error."""
pass
But it is not clear how to deal with the row by row situation and skipping. Any help from anyone who's dealt with this would greatly appreciated.
documentation is pretty clear:
dry_run is a Boolean which determines if changes to the database are
made or if the import is only simulated. It defaults to False.
raise_errors is a Boolean. If True, import should raise errors. The
default is False, which means that eventual errors and traceback will
be saved in Result instance.
Related
I'm trying to figure it out on how I can show only a specific set of dynamic fields in eav to a unique registered model in my apps.models. But I don't know how to this, I've also read the documents but I can't seem to find anything about it, or maybe I've come across it and didn't understand.
Now, what is happening is that, when I add an attribute in the django admin. It also adds the dynamic field in all the models registered in the eav.
What I want to do is that;
model 1 - dynamic_field1, dynamic_field2, dynamic_field3
model 2 - dynamic_field4, dynamic_field5, dynamic_field6
Btw, I'm currently using the django-eav2 the documentation is in the link. I've found my solution for my initial use case here link
Below codes are basically on how to register my models to the eav. Here is my sample models
class ClientName(models.Model):
name = models.CharField(max_length=250, null=True, blank=True)
description = models.TextField(null=True, blank=True)
is_active = models.BooleanField(default=True)
def __str__(self):
return str(self.name)
class CallDetails(models.Model):
client_name = models.ForeignKey(ClientName, on_delete=models.PROTECT, null=True, blank=True, db_index=True)
letter_info = models.TextField(null=True, blank=True)
def __str__(self):
return str(self.client_name)
class Meta:
verbose_name = 'Call Detail'
ordering = ['client_name']
eav.register(ClientName)
eav.register(CallDetails)
below is my admin.py
class CallDetailsAdminForm(BaseDynamicEntityForm):
model = CallDetails
class CallDetailsAdmin(BaseEntityAdmin):
form = CallDetailsAdminForm
admin.site.register(CallDetails, CallDetailsAdmin)
I was trying to adjust a DateField in one of my models to also show the time (DateTimeField). I ended up also making timezone adjustments. After all I decided to not use the time and deleted the additional code and set the field back to DateField. Migrations are made and migrated. Now when trying to access an object from the model either via the page or admin page I receive the error:
invalid literal for int() with base 10: b'24 22:00:00'
So after trying a few things I just wanted to delete the objects in the model using the admin page. This also resulted in the above error.
It seems every page relying on an object from that model throws the error.
Is there a way to force delete objects?
Can you recommend any other clean up methods?
The model is defined as:
class PieceInstance(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text='Unique ID for this particular Piece across whole system')
piece = models.ForeignKey('Piece', on_delete=models.SET_NULL, null=True)
version = models.CharField(max_length=200)
date_claimed = models.DateField(null=True, blank=True)
claimant = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)
date_sent_to_claimant = models.DateField(null=True, blank=True)
PIECE_STATUS = (
('n', 'Not Claimable'),
('a', 'Available'),
('r', 'Reserved'),
('c', 'Claimed'),
)
status = models.CharField(
max_length=1,
choices=PIECE_STATUS,
blank=True,
default='a',
help_text='Piece Availability',
)
#property
def claimed_overdue(self):
days_till_claimed_overdue = 7
if self.date_claimed and date.today() > self.date_claimed + timedelta(days=days_till_claimed_overdue):
return True
return False
class Meta:
ordering = ['date_claimed']
permissions = (('can_mark_sent_to_claimant', 'Set Piece Instance as sent to claimant'),)
def __str__(self):
return f'{self.id} ({self.piece.title})'
Since my project is not big I decided to drop the whole database and set it up again from scratch.
I used the accepted answer of this question
Note that you also have to set up all users again (including the superuser)
I'm working on a Django project generated via Mezzanine. I've been able to create my models, however I want to have a form where an admin can select from a list to assign a value in a many to many or a one to many relationship. For example, I have a model for Schemas:
class Schema(AutoCreatedUpdatedMixin, SoftDeleteMixin):
"""List of all Schemas in a given database"""
name = models.CharField(max_length=128, null=False)
status = models.BooleanField(max_length=128, null=False, default=True, verbose_name="Is Active")
description = models.CharField(max_length=65535, null=True, blank=True, default=None)
database = models.ForeignKey(Database, on_delete=models.CASCADE)
pull_requests = models.ManyToManyField(Link)
questions = models.ManyToManyField(Question, blank=True)
comments = models.ManyToManyField(Comment, blank=True)
technical_owners = models.ManyToManyField(Employee, related_name='technical_owners_schemas', blank=True)
business_owners = models.ManyToManyField(Employee, related_name='business_owners_schemas', blank=True)
watchers = models.ManyToManyField(Employee, related_name='watchers_schemas', blank=True)
def __unicode__(self):
return "{}".format(self.name)
And I have a model for Employees
class Employee(AutoCreatedUpdatedMixin, SoftDeleteMixin):
"""List of people with any involvement in tables or fields: business or technical owners, developers, etc"""
name = models.CharField(max_length=256, blank=False, null=False, default=None, unique=True)
email = models.EmailField(blank=True, null=True, unique=True)
def __unicode__(self):
return "{}".format(self.employee)
An employee can own multiple schemas and a schema can be owned by multiple employees. My database has an active employee in it, however when I try to create a Schema the employee shows up as Employee Object. Rather I would want the form to show the Employee.name. How can I do this? My admin file contains the following:
class SchemasAdmin(admin.ModelAdmin):
list_display = ['name', 'status', 'database', 'description']
ordering = ['status', 'database', 'name']
actions = []
exclude = ('created_at', 'updated_at', 'deleted_at')
First of all are you using python 2 or 3? For 3, the __str__ method should be used instead of __unicode__. I am writing this because it seems that there's a problem with the __unicode__ method of Employee, which although is defined as:
def __unicode__(self):
return "{}".format(self.employee)
th Employee class does not have an employee attribute (unless there's such an attribute in the mixins that class inherits from (AutoCreatedUpdatedMixin, SoftDeleteMixin) but I don't think that is the case.
In any case, the problem is that you haven't defined a propery __str__ (if using python 3) or __unicode__ (for python 2) method on the Employee class - just define it like:
return self.name
and you should see the employee's name in the django admin select fields.
This is are my models i want to relate. i want for collection to appear in the form of occurrence.
class Collection(models.Model):
id = models.AutoField(primary_key=True, null=True)
code = models.CharField(max_length=100, null=True, blank=True)
address = models.CharField(max_length=100, null=True, blank=True)
collection_name = models.CharField(max_length=100)
def __unicode__(self):
return self.collection_name
class Meta:
db_table = u'collection'
ordering = ('collection_name',)
class Occurrence(models.Model):
id = models.AutoField(primary_key=True, null=True)
reference = models.IntegerField(null=True, blank=True, editable=False)
collection = models.ForeignKey(Collection, null=True, blank=True, unique=True),
modified = models.DateTimeField(null=True, blank=True, auto_now=True)
class Meta:
db_table = u'occurrence'
Every time i go to check the Occurrence object i get this error
TemplateSyntaxError at /admin/hotiapp/occurrence/
Caught an exception while rendering: column occurrence.collection_id does not exist
LINE 1: ...LECT "occurrence"."id", "occurrence"."reference", "occurrenc..
And every time i try to add a new occurrence object i get this error
ProgrammingError at /admin/hotiapp/occurrence/add/
column occurrence.collection_id does not exist
LINE 1: SELECT (1) AS "a" FROM "occurrence" WHERE "occurrence"."coll...
What am i doing wrong? or how does ForeignKey works?
The problem is that you have not updated your database table definition since adding the ForeignKey. syncdb doesn't do this for you, as the documentation clearly states. You need to update the SQL manually, or use a tool like South.
Are you sure you mean
collection = models.ForeignKey(Collection, null=True, blank=True, unique=True),
Nullable and Unique? This may not be possible in some databases.
Generally, the unique constraint doesn't seem to make much sense here.
Are you trying to force a 1-to-1 relationship? Use the OneToOneField. http://docs.djangoproject.com/en/1.1/ref/models/fields/#django.db.models.OneToOneField
class Product(models.Model):
...
image = models.ImageField(upload_to=generate_filename, blank=True)
When I use ImageField(blank=True) and do not select image into admin form, an exception occurs.
In django code you can see this:
class FieldFile(File):
....
def _require_file(self):
if not self:
raise ValueError("The '%s' attribute has no file associated with it." % self.field.name)
def _get_file(self):
self._require_file()
...
Django trac has ticket #13327 about this problem, but seems it can't be fixed soon. How to make these field optional?
blank=True should work. If this attribute, which is False by default, is set to True then it will allow entry of an empty value.
I have the following class in my article app:
class Photo(models.Model):
imagename = models.TextField()
articleimage = models.ImageField(upload_to='photos/%Y/%m/%d', blank=True)
I make use of the above class in another class by using the ManyToManyField relationship:
class Article(models.Model):
pub_date = models.DateTimeField(default=timezone.now)
slug = models.SlugField(max_length=130)
title = models.TextField()
photo = models.ManyToManyField(
Photo, related_name='photos', blank=True)
author = models.ForeignKey(User)
body = models.TextField()
categories = models.ManyToManyField(
Category, related_name='articles', null=True)
I want to make images in my articles optional, so blank=True in
photo = models.ManyToManyField(Photo, related_name='photos', blank=True)
is necessary. This allows me to create an article without any images if I want to.
Are you using class Product in any relationship? If so, make sure to set blank=True in the relationship you are using.
Set null=True (see documentation)
class Product(models.Model):
...
image = models.ImageField(upload_to=generate_filename, blank=True, null=True)
If 'optional' means that you want to be able to disregard the image field altogether. Then blank=True, so do the trick. However, if you are still getting the same error, then this means that you are using it's url either in the template somewhere or you are trying to open the path of the image in models.py or views.py ( may be to resize the image or some other backend preprocessing).
That is why it is always suggested to use try - catch block while handling files.