Answer the question
In order to leave comments, you need to log in
How to get different initial models in forms if virew is one, form is one, different urls?
Hey!
models.py
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'),
is required in when opening a new form formsself.fields["models_views"].initial = Models_view.objects.get(id=1),
and aturl(r'^add2/$', views.add, name='add2')
self.fields["models_views"].initial = Models_view.objects.get(id=2)
Answer the question
In order to leave comments, you need to log in
Learn python. How classes work. Learn databases (nomal forms). Learn the basics of djanga
Add and pass an argument to the form's initialization function. But your models are somehow lame.
and as the previous speaker noted, the designation of variables and designations of classes in python are regulated.
In views.py, a good need is:
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})
Problem solved:
models.py
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'),
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question