I have the following structure:
class FeatureType(models.Model):
type = models.CharField(max_length=20)
def __unicode__(self):
return self.type
class Feature(models.Model):
name = models.CharField(max_length=50)
type = models.ForeignKey(FeatureType)
premium = models.BooleanField("Premium Feature", default=False)
def __unicode__(self):
return self.name
What I want to do is when the user is adding a vehicle (the app is for a vehicle inventory), there's a large textbox that will be used to get a list of features from another website by the user copying and pasting them there.
I'm doing fine so far, but what I don't know how to do is, for each feature that's parsed from the textbox, the user will be able to set the type
this feature belongs to. Here's my code so far:
vehicle_form = VehicleForm(request.POST or None)
photos = PhotosFormSet(request.POST or None, request.FILES or None)
features = FeaturesForm(request.POST or None)
if vehicle_form.is_valid() and photos.is_valid() and features.is_valid():
vehicle = vehicle_form.save(commit=False)
vehicle.save()
if features.cleaned_data['external']:
external_set = features.cleaned_data['external'].split('\r\n')
for feature in external_set:
#set featuretype somehow
vehicle_feature, created = Feature.objects.get_or_create(name=feature
, type = featuretype)
feature = vehicle.features.add(vehicle_feature)
photos = PhotosFormSet(request.POST, request.FILES, instance=vehicle)
photos.save()
So how can I enable choosing a feature type for each feature?
What I want to do, ideally, is to have existing features matched to the record...for those features that don't exist, the user will be redirected to another view that will enable him to set the type
for each new feature and subsequently add it to the record.
UPDATE 1 I've modified the code a bit to look like this:
if features.cleaned_data['external']:
new_features = []
external_set = features.cleaned_data['external'].split('\r\n')
for feature in external_set:
try:
vehicle_feature = Feature.objects.get(external_name = feature)
feature = vehicle.features.add(vehicle_feature)
except Feature.DoesNotExist:
new_features.append(feature)
This takes care of getting the existing features....what I want to do now is to have all the features in new_features
passed onto another form after the user saves the current record, where the user will enter further details for each feature.