问题
I am using DAL to provide a selectable dropdown list like this:
class OccupationsModel(models.Model):
Occupation_Code = models.CharField(max_length = 20, primary_key=True)
Occupation_Title = models.CharField(max_length = 150, unique=True)
Occupation_Desc = models.CharField(max_length = 1000)
class Meta:
db_table = 'Occupation_Info'
def __str__(self):
return self.Occupation_Title
Note here that occupation_code is my PK while I am using str to show occupation_title as my display. Mostly everything works fine but then I use instance to prepopulate the form, the title is not displayed. The form field is empty. I have other similar models where the PK is the same as display and those work just fine. So I am pretty sure there is something I am missing here.
Here is my DAL view:
class OccCreateView(CreateView):
model = OccupationsModel
template_name = 'dashboard/input_page.html'
form_class = InputForm
class occautocomplete(autocomplete.Select2QuerySetView):
def get_queryset(self):
qs = OccupationsModel.objects.all().order_by('Occupation_Code')
# Don't forget to filter out results depending on the visitor !
if not self.request.user.is_authenticated:
qs = qs[:3]
if self.q:
qs = qs[:3]
if self.q:
qs = qs.filter(Occupation_Title__icontains = self.q)
return qs
Here is my form:
def miscuserinfo_view(request):
misc_user_info = MiscUserInfoModel.objects.get(user = request.user.id)
if request.method == 'POST':
if form.is_valid():
obj = form.save(commit=False)
# do something here with the form
obj.save()
return HttpResponseRedirect(reverse('registration:userprofile'))
else: # Pre-populate with existing data that user entered before
form = MiscUserInfoForm(instance = misc_user_info)
return render(request, "registration/miscinfo_page.html", {'form': form})
And here is what I see:
Any help is much appreciated. Thanks.
来源:https://stackoverflow.com/questions/61602875/django-autocomplete-light-pk-vs-display-field