英文:
Django FieldError, one to many relationship
问题
The issue you're encountering seems to be related to a field named "project_pictures" that no longer exists in your Project model but is still referenced somewhere in your code or database schema. To resolve this, you should follow these steps:
-
Make sure you have removed all references to the "project_pictures" field in your code, including any previous migrations where it might have been defined.
-
Delete all migration files in your app's "migrations" folder except for the
__init__.py
file. -
Run
python manage.py makemigrations
again to generate new migration files. -
Run
python manage.py migrate
to apply the migrations. -
Check your code and templates for any remaining references to the old "project_pictures" field and update them to use the correct field names, which are "project_images" for your ForeignKey field in the Image model.
-
Make sure you've updated any views, forms, or templates that interact with the Project and Image models to use the correct field names and relationships.
-
Test your Django project to ensure that it's working as expected.
This should help resolve the "Unknown field(s) (project_pictures) specified for Project" error you were encountering.
英文:
The behind my Django project is, that you can post projects, that includes the name, description, creationtime and deadline of the project, alongside images you can add.
In my Django project, I am using the Project and Image models to implement a one-to-many relationship. The Project model represents a project with fields such as project_name, project_description, created_at, and deadline. The Image model represents an image associated with a project and has a foreign key relationship with the Project model.
But when i do python manage.py makemigrations this Error appears:
django.core.exceptions.FieldError: Unknown field(s) (project_pictures) specified for Project
full traceback: Exception in thread django-main-thread:
Traceback (most recent call last):
File "C:\Usersaitc\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 1038, in _bootstrap_inner
self.run()
File "C:\Usersaitc\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 975, in run
self._target(*self._args, **self._kwargs)
File "C:\Django2\env\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper
fn(*args, **kwargs)
File "C:\Django2\env\Lib\site-packages\django\core\management\commands\runserver.py", line 133, in inner_run
self.check(display_num_errors=True)
File "C:\Django2\env\Lib\site-packages\django\core\management\base.py", line 485, in check
all_issues = checks.run_checks(
^^^^^^^^^^^^^^^^^^
File "C:\Django2\env\Lib\site-packages\django\core\checks\registry.py", line 88, in run_checks
new_errors = check(app_configs=app_configs, databases=databases)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Django2\env\Lib\site-packages\django\core\checks\urls.py", line 42, in check_url_namespaces_unique
all_namespaces = _load_all_namespaces(resolver)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Django2\env\Lib\site-packages\django\core\checks\urls.py", line 61, in _load_all_namespaces
url_patterns = getattr(resolver, "url_patterns", [])
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Django2\env\Lib\site-packages\django\utils\functional.py", line 57, in __get__
res = instance.__dict__[self.name] = self.func(instance)
^^^^^^^^^^^^^^^^^^^
File "C:\Django2\env\Lib\site-packages\django\urls\resolvers.py", line 715, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
^^^^^^^^^^^^^^^^^^^
File "C:\Django2\env\Lib\site-packages\django\utils\functional.py", line 57, in __get__
res = instance.__dict__[self.name] = self.func(instance)
^^^^^^^^^^^^^^^^^^^
File "C:\Django2\env\Lib\site-packages\django\urls\resolvers.py", line 708, in urlconf_module
return import_module(self.urlconf_name)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Usersaitc\AppData\Local\Programs\Python\Python311\Lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "<frozen importlib._bootstrap>", line 1206, in _gcd_import
File "<frozen importlib._bootstrap>", line 1178, in _find_and_load
File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 690, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 940, in exec_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "c:\Django2\Zimmer\zimmer\zimmer\urls.py", line 9, in <module>
path('', include('projekte.urls')),
^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Django2\env\Lib\site-packages\django\urls\conf.py", line 38, in include
urlconf_module = import_module(urlconf_module)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Usersaitc\AppData\Local\Programs\Python\Python311\Lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "<frozen importlib._bootstrap>", line 1206, in _gcd_import
File "<frozen importlib._bootstrap>", line 1178, in _find_and_load
File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 690, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 940, in exec_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "c:\Django2\Zimmer\zimmer\projekte\urls.py", line 2, in <module>
from . import views
File "c:\Django2\Zimmer\zimmer\projekte\views.py", line 3, in <module>
from projekte.forms import ProjectForm
File "c:\Django2\Zimmer\zimmer\projekte\forms.py", line 4, in <module>
class ProjectForm(forms.ModelForm):
File "C:\Django2\env\Lib\site-packages\django\forms\models.py", line 321, in __new__
raise FieldError(message)
django.core.exceptions.FieldError: Unknown field(s) (project_pictures) specified for Project
So i did a model, named "Project", that holds the project name, project description, when it was created and when the deadline is.
Then i did return self.project_name
, so when i print or display a Project model, it should be represented by its project_name field value.
After that i did another model, called "Image", that has the field project, which has a relationship with the object "Project", then i did on_delete=models.CASCADE
, so when i delete the Project, everything related with that object gets also deleted.
I did related_name='project_images'
, to set the reverse relation name from the Project model back to the Image model. The idea behind it is, that it allows to access the set of Image objects associated with a Project instance. In my model, i can access the set of Image objects from a Project object using the project_images attribute.
This is my models file:
from django.db import models
class Project(models.Model):
project_name = models.CharField(max_length=30)
project_description = models.CharField(max_length=2000)
created_at = models.DateTimeField(auto_now_add=True)
deadline = models.DateTimeField(null=True, blank=True)
def __str__(self):
return self.project_name
class Image(models.Model):
project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='project_images')
image = models.ImageField(null=True, blank=True, upload_to="images/")
def __str__(self):
return self.image.name
But for some reason it doesnt work, i googled it and asked chatgpt for help, but that didnt help much either. I dont understand the Error: django.core.exceptions.FieldError: Unknown field(s) (project_pictures) specified for Project.
But i have some ideas, where it might come from. In my previous model there was a field that was called "project_pictures" and looked like that:
from django.db import models
class Project(models.Model):
project_name = models.CharField(max_length=30)
project_description = models.CharField(max_length=5000)
project_pictures = models.ImageField(null=True, blank=True, upload_to="images/")
created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True)
deadline = models.DateTimeField(null=True, blank=True)
def __str__(self):
return self.project_name
I thought, the issue lied in the model Project, because it still had the column "project_pictures" and might tries to do something with it, when i try to make the migration. Then i deleted that column, but then the exact same Error appeared. Im clueless where the error is, since now, i dont even have a field called "project_pictures". And if the error is related with a FieldError, it only can be the Model that does the issues, right?
My goal is, that i can create a project, where i can add more than one image.
I am more than greatful and thankful, if you can help me.
答案1
得分: 0
I found out about where the problem was, it was in my forms.py file.
我找到了问题所在,它在我的forms.py文件中。
I forgot to delete, in the Meta class, 'project_pictures'.
我忘记在Meta类中删除了'project_pictures'。
英文:
I found out about where the problem was, it was in my forms.py file.
I forgot to delete, in the Meta class, 'project_pictures'.
How it looked like:
from django import forms
from .models import Project
class ProjectForm(forms.ModelForm):
class Meta:
model = Project
fields = ['project_name', 'project_description', 'deadline', 'project_pictures']
widgets = {
'deadline': forms.DateTimeInput(attrs={'type': 'date'}),
}
How it lookes like fixed:
class ProjectForm(forms.ModelForm):
class Meta:
model = Project
fields = ['project_name', 'project_description', 'deadline', 'project_pictures']
widgets = {
'deadline': forms.DateTimeInput(attrs={'type': 'date'}),
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论