Reputation: 447
I want create a simple form in my app with foreign key. I've two databases, a is default of Django, and the other is a legacy database.
The message of error that show is this: Table 'django.customer' doesn't exist. But I want select my other database, not Django. How I do this?
This is my model:
from django.db import models
from register.models import Customer
class Service(models.Model):
# ..
customer = models.ForeignKey('register.Customer', db_column='customer')
# ..
This is other model in other app.
class Customer(models.Model):
codigo = models.AutoField(primary_key=True)
Both apps are in other database and not of Django.
My settings.py:
DATABASES = {
'default': {
'NAME': 'django',
'ENGINE': 'django.db.backends.mysql',
'USER': 'my-user',
'PASSWORD': 'my-password',
'HOST': '',
'PORT': ''
},
'other-database': {
'NAME': 'other-database',
'ENGINE': 'django.db.backends.mysql',
'USER': 'my-user',
'PASSWORD': 'my-password',
'HOST': '',
'PORT': ''
}
}
In the HTML I put this:
{{ form_service }}
This my forms.py
from attendance.models import Service
from register.models import Customer
from django.http import HttpResponseRedirect, HttpResponse
from django.core.exceptions import ValidationError
class FormService(ModelForm):
class Meta:
model = Service
fields = ('my_fields', 'my_fields', 'customer')
And this my views.py
def service(request):
form_service = FormService()
return render(request, 'service.html', {'form_service': form_service})
I think that the error is here. Perhaps I've had to define my other database, it should select in Django database.
I tried this, but not worked.
def service(request):
queryset = Customer.objects.using('other-database').all()
form_service = FormService(instance = queryset)
return render(request, 'service.html', {'form_service': form_service})
Upvotes: 2
Views: 886
Reputation: 309009
Your code instance = queryset
doesn't make sense, because instance
should be a Service instance for the form, not a queryset of Customer instances.
Try setting the queryset of the field in the form's __init__
method.
class FormService(ModelForm):
def __init__(self, *args, **kwargs):
super(FormService, self).__init__(*args, **kwargs)
self.fields['customer'].queryset = Customer.objects.using('other-database').all()
class Meta:
model = Service
fields = ('my_fields', 'my_fields', 'customer')
If that doesn't work, please update your question and post the full traceback.
Upvotes: 1