class Models_view(models.Model):
view_name = models.CharField(max_length=100)
class Models_view(models.Model):
name = models.CharField(max_length=100)
models_views = models.ForeignKey(Models_view)
class ModelForm(forms.ModelForm):
class Meta:
model = Model
def __init__(self, *args, **kwargs):
super(ModelForm, self).__init__(*args, **kwargs)
self.fields["models_views"].initial = Models_view.objects.get(id=1)
def add(request, template_name="lbforum/form_add.html" ):
if request.method == 'POST':
f = ModelForm(request.POST)
if f.is_valid():
f.save()
return HttpResponseRedirect(reverse("models"))
else:
f = ModelForm()
ctx = {'form': form}
return render(request, template_name, ctx)
url(r'^add1/$', views.accessories_add, name='accessories_add'),
url(r'^add2/$', views.accessories_add, name='accessories_add1'),
url(r'^add1/$', views.add, name='add1'),
необходимо в при открытии новой формы formsself.fields["models_views"].initial = Models_view.objects.get(id=1),
а при url(r'^add2/$', views.add, name='add2')
self.fields["models_views"].initial = Models_view.objects.get(id=2)
from django.shortcuts import get_object_or_404
...
url_name = request.resolver_match.url_name
if url_name == 'add1':
pk = 1
elif url_name == 'add2':
pk = 2
obj = get_object_or_404(PleaseModelNormalName, pk=pk)
f = ModelForm(request.POST, initial={'models_views': obj})
class Models_view(models.Model):
view_name = models.CharField(max_length=100)
class Model(models.Model):
name = models.CharField(max_length=100)
models_views = models.ForeignKey(Models_view)
class ModelForm(forms.ModelForm):
class Meta:
model = Model
def add(request, view=None, template_name="lbforum/form_add.html" ):
if request.method == 'POST':
f = ModelForm(request.POST)
if f.is_valid():
f.save()
return HttpResponseRedirect(reverse("models"))
else:
if view == 1:
f = ModelForm(initial={'models_views': Models_view.objects.get(id=1)}) # в этом вся фишка
else:
f = ModelForm(initial={'models_views': Models_view.objects.get(id=2)}) # в этом вся фишка
ctx = {'form': f}
return render(request, template_name, ctx)
url(r'^add1/$', views.add, {'view': 1}, name='add1'),
url(r'^add2/$', views.add, name='add2'),