# models.py
class Topic(models.Model):
"""the Topic class"""
name = models.CharField(unique=True, max_length=20)
def __str__(self):
return self.name
class LessonsLearned(models.Model):
"""the Lessons Learned class"""
time_created = models.DateTimeField(auto_now_add=True)
creator = models.ForeignKey(User)
topic = models.ForeignKey(Topic)
text = models.TextField(max_length=3000)
def get_absolute_url(self):
return reverse('lessons_learned_detail', kwargs={'pk': self.pk})
# lookups.py
class TopicLookup(ModelLookup):
model = Topic
search_fields = ('name__icontains', )
def get_item_label(self, item):
"""The label is shown in the drop down menu of search results."""
return item.name
def get_item_id(self, item):
"""The id is the value that will eventually be returned by the field/widget."""
return item.id
def get_item_value(self, item):
"""The value is shown in the input once the item has been selected."""
return item.name
registry.register(TopicLookup)
# forms.py
class LessonsLearnedForm(ModelForm):
topic = AutoCompleteSelectField(lookup_class=TopicLookup, allow_new=True)
class Meta:
model = LessonsLearned
labels = {
'text': "Lessons learned",
}
widgets = {
'text': CharsLeftArea(
attrs={'placeholder': '%d characters max...' % model._meta.get_field('text').max_length}
),
}
exclude = ['topic', 'creator']
def save(self, *args, **kwargs):
topic = self.cleaned_data['topic']
topic.name = " ".join(w.capitalize() for w in topic.name.split())
print(type(topic))
if not Topic.objects.filter(name=topic.name).exists():
# If new topic
print("Creating New object")
topic = Topic.objects.create(name=topic.name)
topic = Topic.objects.get(name=topic.name)
self.instance.topic = topic
return super(LessonsLearnedForm, self).save(*args, **kwargs)
If I don't exclude the default 'topic' field, the order in which the two form field shows is correct.
But when I submit a new topic, or submit a topic name which already exists (but not by selecting the topic object from the suggestion dropdown list), Django would raise an ValueError complaining that the "Topic" instance isn't saved in the data base.
Please help me.