I'm struggling with CreateView get_initial() in django1.7
I have a modelA detail page with an "add ModelB" (modelB has FK to ModelA)
button.
When I hit that button, I want the new ModelB obj to have the modelA FK set. So
in the ModelB CreateView I have a get_initial that uses the slug to set the
modela.
When I run the code below , the modelB wont save ("missing modelA_id")
forms.py doesn't include modela field because I want modela set without ability
to edit it. Have tried including it, and excluding from the template - always
get's a "modela is required field" error.
What am I doing wrong or what test can I run to determine why the
field isn't being set?
models.py:
class ModelA(models.Model):
name = models.CharField(max_length=30)
class ModelB(models.Model):
name = models.CharField(max_length=30)
modela = models.ForeignKey(ModelA, related_name='moda')
urls.py:
url(r'^model/add/$', views.ModelAAdd.as_view(), name='modelA_add'),
url(r'^model/(?P<slug>[-\w]+)/$', views.ModelADetail.as_view(),
name='modelA_detail'),
url(r'^model/(?P<slug>[-\w]+)/modelb/add/$',
views.ModelBAdd.as_view(), name='modelB_add'),
views.py:
class ModelBAdd(generic.CreateView):
fields = ['modela', 'name']
form_class = ModelBAddForm
model = ModelB
template_name = 'jobs/modelB_form.html'
def get_initial(self):
slug = self.kwargs['slug']
modela = ModelA.objects.get(slug=slug)
print
modela.id, modela # <- prints correct details in log
return {'modela':
modela.id }
forms.py
class ModelBAddForm(forms.ModelForm):
class Meta:
fields = ['name']
model = ModelB
widgets = {
'name': forms.TextInput(attrs={'class':'form-control'}),
}
--
You have to be really clever to come up with a genuinely dangerous
thought. I am disheartened that people can be clever enough to do that
and not clever enough to do the obvious thing and KEEP THEIR IDIOT
MOUTHS SHUT about it, because it is much more important to sound
intelligent when talking to your friends.
This post was STUPID.
-----------------------------------------------------------------------------------------------------------
The Most Terrifying Thought Experiment of All Time
http://www.slate.com/articles/technology/bitwise/2014/07/roko_s_basilisk_the_most_terrifying_thought_experiment_of_all_time.html