I am currently working on a Django project where I'm using the django-import-export library to import CSV data into my models through the Django admin interface. I have set up resources, models, and made necessary changes in the admin, but I'm facing validation errors during the import process.
I have the following structure in my Django project:
models.py: Contains the definitions of various models like PlayStyles, Coaches, Stadiums, Leagues, Teams, Players, Matches, and Statistics.
resources.py: Includes corresponding ModelResource classes for each model.
admin.py: Configures the Django admin interface to use the ModelResource classes for data import/export.
CSV Files: I have CSV files for each model with data to be imported.
Despite setting up the resources correctly, I am encountering issues when importing CSV files for certain models, specifically for Teams. The error message mentions validation errors related to foreign key fields (stadium, coach, and league).
Here's a snippet of my relevant code: models.py:
# ... (models for PlayStyles, Coaches, Stadiums, Leagues, etc.)
class Teams(models.Model):
name = models.CharField(max_length=100)
established_year = models.IntegerField()
stadium = models.ForeignKey(Stadiums, on_delete=models.CASCADE)
coach = models.ForeignKey(Coaches, on_delete=models.CASCADE)
league = models.ForeignKey(Leagues, on_delete=models.CASCADE)
number_of_titles = models.IntegerField()
resources.py:
# ... (resources for PlayStyles, Coaches, Stadiums, Leagues, etc.)
class TeamsResource(resources.ModelResource):
class Meta:
model = Teams
fields = ('name', 'established_year', 'stadium', 'coach', 'league', 'number_of_titles')
admin.py:
# ... (admin configurations for PlayStyles, Coaches, Stadiums, Leagues, etc.)
class TeamsAdmin(admin.ModelAdmin):
list_display = ('name', 'established_year', 'stadium', 'coach', 'league', 'number_of_titles')
resource_class = TeamsResource
admin.site.register(Teams, TeamsAdmin)
csv file teams.csv:
name,established_year,stadium,coach,league,number_of_titles
TeamA,1990,Old Trafford,Jurgen Klopp,Premier League,5
TeamB,1985,Camp Nou,Pep Guardiola,La Liga,3
I suspect that the issue is related to how I'm handling foreign key fields during the import. Any guidance on resolving this issue would be greatly appreciated.