Reputation: 211
Hy guys sorry for this post but i need help with my application, i need optimize my view. I have 5 models, how i can do this?
def save(request):
# get the request.POST in content
if request.POST:
content = request.POST
dicionario = {}
# create a dict to get the values in content
for key,value in content.items():
# get my fk Course.objects
if key == 'curso' :
busca_curso = Curso.objects.get(id=value)
dicionario.update({key:busca_curso})
else:
dicionario.update({key:value})
#create the new teacher
Professor.objects.create(**dicionario)
my questions are?
1 - How i can do this function in a generic way? Can I pass a variable in a %s to create and get? like this way ?
foo = "Teacher" , bar = "Course"
def save(request, bar, foo):
if request post:
...
if key == 'course' :
get_course = (%s.objects.get=id=value) %bar
...
(%s.objects.create(**dict)) %foo ???
i tried do this in my view but don't work =/, can somebody help me to make this work ? Thanks
Upvotes: 0
Views: 86
Reputation: 80031
Instead of doing this all manually you should use ModelForms. That way you can simply create a form that will automatically create your object upon calling save()
.
Example:
class ProfessorForm(ModelForm):
class Meta:
model = Professor
def save(request):
if request.method == 'POST':
form = ProfessorForm(request.POST)
if form.is_valid():
form.save()
Upvotes: 3
Reputation: 2049
Since you have more than one of these forms, you actually want formsets: http://docs.djangoproject.com/en/dev/topics/forms/formsets/
The docs do a fantastic job of describing how to throw a form with a queryset together into a formset to edit more than one thing at a time :)
Upvotes: 0