0
votes

models.py:

class MODEL(models.Model):
    ModelName = models.CharField(max_length = 128, unique = True)
    URL_Slug = models.SlugField(unique = True)
    ...

class Maker(models.Model):
    maker = models.CharField(max_length = 128, unique = True)
    URL_Slug = models.SlugField(unique = True)
    ...
class Truck(models.Model):
    MODEL = models.ForeignKey(MODEL)
    CarID = models.CharField(max_length = 10, unique = True, null = False)
    Maker = models.ForeignKey(Maker)   
    year = models.IntegerField(default = 0)
    def __unicode__(self):
        return self.CarID

forms.py:

class MODELForm(forms.ModelForm):
    ModelName = forms.CharField(max_length = 128, help_text = 'Enter the NEW model name')
    URL_Slug = forms.SlugField(widget = forms.HiddenInput(), required = False)

    class Meta:
        model = MODEL
        fields = ('ModelName', )

class MakerForm(forms.ModelForm):
    maker = forms.CharField(max_length = 128, help_text = 'Enter the NEW maker')
    URL_Slug = forms.SlugField(widget = forms.HiddenInput(), required = False)

    class Meta:
        model = Maker
        fields = ('maker', )

class TruckForm(forms.ModelForm):
    MODEL = forms.CharField(max_length = 128, help_text = 'Enter the NEW model name')
    CarID = forms.CharField(max_length = 10, help_text = 'Enter the NEW truck ID')
    Maker = forms.CharField(max_length = 128, help_text = 'Enter the NEW maker')   
    year = forms.IntegerField(help_text = 'Enter the year of production')

    class Meta:
        model = Truck
        fields = ('MODEL', 'CarID', 'Maker', 'year')

views.py:

def add_Truck(request):
    form = TruckForm()

    if request.method == 'POST':
        form = TruckForm(request.POST)
        if form.is_valid():
            form.save(commit = True)
            return index(request)

        else:
            print(form.errors)
    return render(request, 'APP/addTruck.html', {'form': form})

HTML File:

<!DOCTYPE html>
<html>
    <body>
        <div>
            <form id = "Truck" method = "post" action = "/APP/NewTruck/">
                {%csrf_token%}
                {% for field in form.visible_fields %}
                    {{field.errors}}
                    {{field.help_text}}
                    {{field}}<br/>
                {% endfor %}
                <input type = "submit" name = "submit" value = "Create Truck">
            </form>
        </div>
    </body>
</html>

I am trying to create a new object in the addTruck.html, I guest that because of MODEL and Maker are foreign keys, when creating Truck object, MODEL and Maker field should also be object.

Traceback:

Here is the Traceback from terminal Macbook:

-

[07/Aug/2017 09:14:04] "GET /APP/NewTruck/ HTTP/1.1" 200 1240
Internal Server Error: /APP/NewTruck/ Traceback (most recent call
last): File
"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/handlers/exception.py", line 39, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File
"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/apple/WebWorkshop/TKTrading/APP/views.py", line 88, in
add_Truck if form.is_valid(): File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/forms/forms.py", line 169, in is_valid return self.is_bound and not self.errors File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/forms/forms.py", line 161, in errors self.full_clean() File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/forms/forms.py", line 372, in full_clean self._post_clean() File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/forms/models.py", line 388, in _post_clean self.instance = construct_instance(self, self.instance, opts.fields, opts.exclude) File
"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/forms/models.py", line 60, in construct_instance f.save_form_data(instance, cleaned_data[f.name]) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/fields/init.py", line 833, in save_form_data setattr(instance, self.name, data) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/fields/related_descriptors.py", line 211, in set self.field.remote_field.model._meta.object_name, ValueError: Cannot assign "u'Wing'": "Truck.MODEL" must be a "MODEL" instance.
[07/Aug/2017 09:14:42] "POST /APP/NewTruck/ HTTP/1.1" 500 93290

1
add full tracebackArpit Solanki

1 Answers

1
votes

In your TruckForm,

MODEL = forms.CharField(max_length = 128, help_text = 'Enter the NEW model name')

in your models,

MODEL = models.ForeignKey(MODEL)

ForeignKey fields need to be instances of the corresponding models, rather than plain text. Error message is very specific about that. In your case, if you want to create new model for a new truck everytime, you may need to override the save() method of your ModelForm for appropriate reasons. Or else if you want to choose a model from existing MODELs, either you could let Django use the default select widget for the field or you can override that too by defining a custom widget.

MODEL = forms.ModelChoiceField(queryset=MODEL.objects.all())
#something like this.