Hello,
from django.db import models
def create_a():
return ModelA.objects.create(name='<default-name>').id
class ModelA(models.Model):
name = models.CharField(max_length=123)
class ModelB(models.Model):
reference = models.ForeignKey(ModelA, default=create_a)
-- I recently stumbled upon a problem with Django ModelForms which is that the default value gets called on fields not even selected by the form.
Here is an exampel:
// models.py
def create_a():
return ModelA.objects.create(name='<default-name>').id
class ModelA(models.Model):
name = models.CharField(max_length=123)
class ModelB(models.Model):
reference = models.ForeignKey(ModelA, default=create_a)
// views.py
from django.http.response import HttpResponse
from django.forms import ModelForm
from abc123.models import ModelA, ModelB
class MyForm(ModelForm):
class Meta:
model = ModelB
fields = []
def my_view(request):
MyForm()
return HttpResponse('abc123')
from django.http.response import HttpResponse
from django.forms import ModelForm
from abc123.models import ModelA, ModelB
class MyForm(ModelForm):
class Meta:
model = ModelB
fields = []
def my_view(request):
MyForm()
return HttpResponse('abc123')
// <end of code>
Now every time I call the MyForm init function (loads the my_view) the create_a functions gets called and there for a new instance if ModelA gets created even though I set fields to an empty list in the MyForms Meta class.
I can't believe this is intended or maybe I'm missing something answers would be apprecitated, Thanks.
// Jesper Jansson
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/f1636ef0-74ff-4fb8-8d6c-476c7d4bbce4%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
No comments:
Post a Comment