1

New to using Django over here. I am trying to create a DJango form that will save data to the database. To do this, I am using CreateView

When calling the URL that is to "do the work", I have it set up as follows (so, a parameter is being passed in as well)

url(r'^owner/contacts/add/(?P<tenantid>[0-9]+)/$', views.MstrstoreheadcontactCreateView.as_view(), name='owner-contact-add'),

Problem:

When trying to save data to the DB, I get an error that seems to be due to some fields not being set properly

enter image description here

the exact error message I am getting is:

The above exception (ORA-02291: integrity constraint (ORAAPPS.SYS_C009216) violated - parent key not found) was the direct cause

This is how the Model is defined:

class Mstrstoreheadcontact(models.Model):
    tenantid = models.ForeignKey('Mstrauthowner', models.DO_NOTHING, db_column='tenantid', blank=True, null=True)
    contactid = models.BigIntegerField(primary_key=True)
    genderid = models.BigIntegerField(blank=True, null=True)
    firstname = models.CharField(max_length=20, blank=True, null=True)
    lastname = models.CharField(max_length=20, blank=True, null=True)
    officephoneno = models.CharField(max_length=20, blank=True, null=True)
    cellphoneno = models.CharField(max_length=20, blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'MstrStoreHeadContact'

it was created using the inspectdb option (used to auto-generate classes for tables that already exist in a database)

This is how the CreateView is being defined in views.py

class MstrstoreheadcontactCreateView( CreateView ):
    model = Mstrstoreheadcontact
    fields = [ 'firstname', 'lastname', 'officephoneno', 'cellphoneno']

    def form_valid(self, form):
        self.kwargs['tenantid'] = 10

        # returning rendered page
        super(MstrstoreheadcontactCreateView, self).form_valid(form)
        return render(self.request, self.template_name,
                      self.get_context_data(form=form))

    def get_context_data(self, **kwargs):
        ctx = super(MstrstoreheadcontactCreateView, self).get_context_data(**kwargs)
        ctx['tenantid'] = self.kwargs['tenantid']
        return ctx

My understanding was

that the attributes defined with "fields" were the ones that were to be seen on the form. Yet, when doing a "save", the other fields look as though they are being ignored (as seen in the error log). enter image description here

Right now, self.kwargs['tenantid'] = 10is being set manually in the CreateView code. How can I fix this so that it will take a value that is passed with the URL. Why does it look as though the fields being set to None on insert?

Update

@dirkgroten - thanks for the response! I added the function as instructed. This is the error that I got.

TypeError at /masterdata/owner/contacts/add/10/ __init__() got an unexpected keyword argument 'tenantid'
Request Method: GET
Request URL: http://127.0.0.1:8000/masterdata/owner/contacts/add/10/
Django Version: 1.11.1
Exception Type: TypeError
Exception Value: __init__() got an unexpected keyword argument 'tenantid'

I saw this as well: Getting __init__() got an unexpected keyword argument 'instance' with CreateView of Django

How to set ForeignKey in CreateView?

Do I need to create a form to go with the view?

Casey Harrils
  • 2,793
  • 12
  • 52
  • 93

2 Answers2

0

The only thing the form_valid() method does is save the form. So by setting self.kwargs['tenanted'] you're not making any changes to the form. You should instead override get_form_kwargs():

def get_form_kwargs(self):
    kwargs = super(MyCreateView, self).get_form_kwargs()
    kwargs.update({'tenantid': 10})
    # You also want to add the contactid, since that's the primary key and is 
    # the actual field the database requires.
    kwargs.update({'contactid': ...})
    return kwargs
dirkgroten
  • 20,112
  • 2
  • 29
  • 42
0

Made the following changes, now the data saves into the DB with no issue. I followed the instructions from the documentation and added "get_absolute_url" to the Model (it was not there before)

models.py

class Mstrstoreheadcontact(models.Model):
  [.. snip ..]
    # as instructed by
    # http://django.readthedocs.io/en/latest/topics/class-based-views/generic-editing.html#model-forms
    def get_absolute_url(self):
        return reverse('masterdata:owner-contact-details', kwargs={'pk': self.contactid}

views.py

class MstrstoreheadcontactCreateView( CreateView ):
    model = Mstrstoreheadcontact
    fields = [ 'firstname', 'lastname', 'genderid', 'officephoneno', 'cellphoneno']

    def form_valid(self, form):
        contact = form.save(commit=False)
        contact.tenantid = Mstrauthowner.objects.get(tenantid=self.kwargs['tenantid'])
        return super(MstrstoreheadcontactCreateView, self).form_valid(form)

urls.py

urlpatterns = [
    url(r'^owner/(?P<pk>[0-9]+)/contact/details/$', views.MstrstoreheadcontactDetailsView.as_view(), name='owner-contact-details'),
    url(r'^owner/(?P<tenantid>[0-9]+)/contacts/add/$', views.MstrstoreheadcontactCreateView.as_view(),
        name='owner-contact-add'),
]
Casey Harrils
  • 2,793
  • 12
  • 52
  • 93