Slow response in django - python

Currently I am inspecting a django queries(django-rest-framework) with django debug toolbar. The postgres database query time is about 100ms which is ok. But the response time took about 6 sec., which is slow.
I found that the slowest(takes about 4 sec.) function is this:
#transaction.atomic
def create(self, *args, **kwargs):
response = super(PersonView, self).create(*args, **kwargs)
data = response.data
product_data = data['packages'][0]['product']
person = Person.objects.get(pk=data['id'])
if not person.info:
product = Product.objects.get(pk=product_data['id'])
PersonItem.objects.create(person=person, product=product)
response.data = PersonSerializer(person).data
return response
Any ideas why the response is so slow or why this function takes so long ?
Edit:
This is my PersonSerializer class.
class PersonSerializer(serializers.ModelSerializer):
person_items = PersonItemSerializer(many=True, read_only=True)
address = AddressSerializer(read_only=True)
office_address = serializers.SerializerMethodField('get_office_address')
status = ChoiceWithNameField(choices=Person.STATUS_CHOICES)
source = ChoiceWithNameField(
choices=Person.SOURCE_CHOICES, required=False)
closing_person = ClosingPersonSerializer(read_only=True)
is_upfront_person = serializers.BooleanField(read_only=True)
has_discount = serializers.BooleanField(read_only=True)
payment_method = serializers.CharField(read_only=True)
user_email = serializers.CharField(
read_only=True, source='user.email')
user_display_name = serializers.CharField(
read_only=True, source='user.display_name')
billing_display_address = serializers.SerializerMethodField(
'get_billing_display_address')
real_estate_display_address = serializers.SerializerMethodField(
'get_real_estate_display_address')
net_total = serializers.DecimalField(read_only=True, source='net_total')
gross_total = serializers.DecimalField(read_only=True, source='gross_total')
tax = serializers.DecimalField(read_only=True, source='tax_total')
coupon_net_total = serializers.DecimalField(read_only=True,
source='coupon_net_total')
coupon_gross_total = serializers.DecimalField(read_only=True,
source='coupon_gross_total')
class Meta:
model = Person
policy_class = PersonPolicy
def get_billing_display_address(self, obj):
try:
address = obj.address
except Address.DoesNotExist:
pass
else:
return "{0} {1}, {2}, {3}".format(
address.house_name_number, address.address_2, address.town,
address.postcode)
def _filter_products(self, products):
user = getattr(self.context.get('request'), 'user', None)
if not user or not user.is_staff:
products = products.filter(admin_only=False)
return products
def _as_person_items(self, person, products):
persons = [PersonItem(name=p.name, description=p.description,
person=person,
price=p.total_up_front,
product=p) for p in products]
return persons
def get_packages(self, person):
products = self._filter_products(person.packages)
return PersonItemMinimalSerializer(
self._as_person_items(person, products),
many=True).data
def get_office_address(self, i):
try:
office_address = i.addresses.get(address_type=Address.ADDRESS)
except Address.DoesNotExist:
return False
return AddressSerializer(office_address, read_only=True).data
def get_real_estate_display_address(self, obj):
try:
address = obj.office_address
except Address.DoesNotExist:
pass
else:
return "{0} {1}, {2}, {3}".format(
address.house_name_number, address.address_2,
address.town, address.postcode)

Related

Status: Select a valid choice. 1 is not one of the available choices Django 3

Here i am using Django 3.0 and Python 3.7.
When i am trying to update the user phone number or email id i am getting this issue.
Here is my views.py:
class ClientUserInfoUpdate(CustomAdminMixin, UpdateView):
model = ClientUser
template_name = "core/user_info_mutiple_edit_form.django.html"
form_class = ClientUserInfoUpdateForm
user = None
methods = None
def get_success_url(self):
return reverse("admin_user_update", args=[self.user.pk])
def get_form_kwargs(self):
kwargs = super(ClientUserInfoUpdate, self).get_form_kwargs()
self.user = kwargs['instance']
self.methods = self.user.get_userinfodata()
kwargs['user'] = self.user
kwargs['methods'] = self.methods
return kwargs
def get_context_data(self, **kwargs):
context = super(ClientUserInfoUpdate, self).get_context_data(**kwargs)
context['user'] = self.user
context['methods'] = self.methods
context['countries'] = countries_sorted
for method in ContactInfoMethod.objects.all():
context['types_' + method.name.lower()] = ContactInfoMethodType.objects.types_by(method.name)
return context
Here is my forms.py:
class ClientUserInfoUpdateForm(forms.ModelForm):
user = None
methods = None
# sort of a copy of fieldsets, but utilising the dynamic capabiliities of the form
#formsections = []
new_info = []
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user')
self.methods = kwargs.pop('methods')
super(ClientUserInfoUpdateForm, self).__init__(*args, **kwargs)
#self.formsections = []
# auto generate the form based upon self.methods (!!!)
for dm in self.methods:
methodtypes = ContactInfoMethodType.objects.types_by(dm['method'].name)
methodtypes_choices = methodtypes.values_list('pk', 'type__name')
if(dm['method'].use_dialling_code):
dialling_code_choices = countries_sorted_with_dial_choices
i = 1
methodname = ""
for info in dm['items']:
fn = info.dynamic_form_field_name()
self.fields[fn] = forms.CharField()
if(dm['method'].name.lower() == "email"):
self.fields[fn] = forms.EmailField()
self.fields[fn].name = fn
self.fields[fn].verbose_name = dm['method'].name
self.fields[fn].label = dm['method'].name + " " + str(i)
self.fields[fn].required = True
self.fields[fn].initial = info.info
self.fields[fn].widget.attrs['class'] = 'span2'
fns = info.dynamic_form_methodtype_select_field_name()
self.fields[fns] = forms.ChoiceField()
self.fields[fns].choices = methodtypes_choices
self.fields[fns].widget.attrs['class'] = 'input-small'
self.fields[fns].initial = info.methodtype.pk
self.fields[fns].required = True
fndc = info.dynamic_form_dialling_code_select_field_name()
if(dm['method'].use_dialling_code):
self.fields[fndc] = forms.ChoiceField()
self.fields[fndc].choices = dialling_code_choices
self.fields[fndc].widget.attrs['class'] = 'span2'
self.fields[fndc].initial = info.dialling_code
self.fields[fndc].required = True
i += 1
#new_fields.append(self.fields[fn])
#self.formsections.append({'legend': dm['method'].name, 'fields': new_fields, 'methodname':dm['method'].name})
def clean(self):
cleaned_data = self.cleaned_data
'''
# e.g.
{
'contactinfo_212695_type_id': u'4',
'contactinfo_249222_type_id': u'1',
'contactinfo_212695': u'paul#padajo.com',
'contactinfo_212694': u'07984 820767',
'contactinfo_249222': u'paul.vidainnovation#gmail.com',
'contactinfo_212693': u'01908 925111',
'contactinfo_212694_type_id': u'8',
'contactinfo_212693_type_id': u'5'
}
'''
# auto generate the form based upon self.methods (!!!)
for dm in self.methods:
for info in dm['items']:
fn = info.dynamic_form_field_name()
fns = info.dynamic_form_methodtype_select_field_name()
if(fn not in self.cleaned_data or fns not in self.cleaned_data):
raise forms.ValidationError("There is some field data missing")
info.info = self.cleaned_data[fn]
info.methodtype_id = self.cleaned_data[fns]
fndc = info.dynamic_form_dialling_code_select_field_name()
if(dm['method'].use_dialling_code):
info.dialling_code = self.cleaned_data[fndc]
# do the save later (!!)
self.new_info.append(info)
del cleaned_data[fn]
del cleaned_data[fns]
if(dm['method'].use_dialling_code):
del cleaned_data[fndc]
return cleaned_data
def save(self, commit=True):
# technically we're not actually working on this object, so just don't commit any changes to it and return
obj = super(ClientUserInfoUpdateForm, self).save(commit=False)
for info in self.new_info:
print("saving info")
print(info)
info.save()
return obj
class Meta:
model = ClientUser
exclude = ['password', 'client', 'email', 'invitation', 'name', 'role',
'last_login', 'minimum_holiday', 'budget_expenses', 'vat']
Here is my reference image of how my edit page looks like
reference image
How can i edit the details of the user like when i am editing the phone number i am getting this issue.

Receiving "NOT NULL constraint failed: home_page._order" error in Django model

I keep receiving the above error and I am still not sure what component of my code is violating this. Below is my modely.py:
def get_image_path(instance, filename):
return os.path.join('photos', str(instance.id), filename)
# Create your models here.
class Textbook(models.Model):
founder = models.CharField(max_length=256)
title = models.CharField(max_length=256)
cover = models.ImageField(upload_to=get_image_path, blank=True, null=True)
def __str__(self):
return self.title
class Page(models.Model):
textbook = models.ForeignKey(Textbook,related_name="pages",blank=True, null=True)
page_title = models.CharField(max_length = 256,blank=True, null=True)
page_num = IntegerRangeField(min_value=0,max_value=256, blank=True, null=True)
def getTextID(self):
return self.textbook.id
def __str__(self):
return self.page_title
def iterSave(self):
pages = self.textbook.pages
MAX_PAGE = pages.aggregate(Max('page_num'))
try:
cpy = pages.get(page_num = self.page_num)
for page in pages:
if page.page_num >= self.page_num:
obj,created = Page.objects.update_or_create(page_title = page.page_title, page_num = page.page_num+1, textbook = page.textbook)
except:
if self.page_num > MAX_PAGE:
obj,created = Page.objects.update_or_create(page_title = self.page_title, page_num = self.page_num+1, textbook = self.textbook)
def save(self, *args,**kwargs):
self.iterSave()
super(Page,self).save(*args, **kwargs)
class Section(models.Model):
page = models.ForeignKey(Page,related_name="sections")
section_title = models.CharField(max_length=256)
text = RichTextField(config_name='awesome_ckeditor')
def __str__(self):
return self.section_title
I understand it has something to do with the query functions but I am not sure what I have done incorrectly to generate this error.
Here is my admin.py if it helps:
admin.site.register(Section)
admin.site.register(Textbook)
admin.site.register(Page)
and here is a helper function I have:
from django.db import models
class IntegerRangeField(models.IntegerField):
def __init__(self, verbose_name=None, name=None, min_value=None, max_value=None, **kwargs):
self.min_value, self.max_value = min_value, max_value
models.IntegerField.__init__(self, verbose_name, name, **kwargs)
def formfield(self, **kwargs):
defaults = {'min_value': self.min_value, 'max_value':self.max_value}
defaults.update(kwargs)
return super(IntegerRangeField, self).formfield(**defaults)
and my views.py:
def index(request):
books = Textbook.objects.all()
ret = {}
for o in books:
ret[o.id] = o
ret['books'] = books
return render(request,'index.html', ret)
def genpage(request, bid = -1, pid = 1):
b = Textbook.objects.get(id = int(bid))
page = b.pages.get(page_num = int(pid))
sections = page.sections.all()
if b.pages.filter(page_num = page.page_num+1).exists():
next_page = page.page_num+1
else:
next_page = -1
if b.pages.filter(page_num = page.page_num-1).exists():
prev_page = page.page_num-1
else:
prev_page = -1
ret = {
'prev_page':prev_page,
'next_page':next_page,
'book':b,
'page_title': page.page_title,
'sections': sections,
}
I am pretty stumped by this because its an error I am so unfamiliar with. The error comes up in relation to calling super in the save function of page but other than that I do not know what to do.
It looks as if your ForeignKey used order_with_respect_to at one point, which adds an _order field to your model.
Now that you have removed order_with_respect_to, you need to remove the field from your database. Hopefully, creating a new migration and migrating will fix the problem.

ModelForm __init__ problems

I've attempted to modify my Django ModelForm __init__ constructor so that it will accept a passed variable ('admin'), look to see if admin == True, and if so, make a couple of fields ('applicant_affirmation' & 'applicant_interest_stmt') display as non-modifiable. The fields are being shown as non-modifiable, as desired, but the .update() function isn't happening because it is not getting past the if form.is_valid check. I've checked for form.non_field_errors and form.errors, but nothing is there. The updates work fine if the __init__ method is commented out.
Any thoughts on what I might be missing? Admittedly I don't have a strong understanding of building a constructor yet. Help would be very much appreciated.
class ApplicationForm(ModelForm):
class Meta:
model = Application
fields = ('program', 'status', 'applicant_affirmation', 'applicant_interest_stmt', 'applicant_school', 'applicant_major', 'applicant_school_2', 'applicant_major_2', 'gpa_univ', 'estimated_grad_semester')
widgets = {
'applicant_interest_stmt': Textarea(attrs={'class': 'form-control', 'rows': 5}),
'estimated_grad_semester': Select(),
}
def __init__(self, admin, *args, **kwargs):
super(ApplicationForm, self).__init__(*args, **kwargs)
if admin:
self.fields['applicant_interest_stmt'].widget.attrs['disabled'] = 'disabled'
self.fields['applicant_affirmation'].widget.attrs['disabled'] = 'disabled'
def clean(self):
from django.core.exceptions import ValidationError
cleaned_data = super(ApplicationForm, self).clean()
applicant_interest_stmt = cleaned_data.get('applicant_interest_stmt')
applicant_affirmation = cleaned_data.get('applicant_affirmation')
if not applicant_interest_stmt:
msg = u'Please provide an interest statement.'
self._errors["applicant_interest_stmt"] = self.error_class([msg])
if not applicant_affirmation:
msg = u'Please check the affirmation checkbox.'
self._errors["applicant_affirmation"] = self.error_class([msg])
return cleaned_data
Application Model:
class Application(models.Model):
id = models.AutoField(primary_key=True)
program = models.ForeignKey(Program, verbose_name="certificate program")
status = models.ForeignKey(Status, verbose_name="application status")
applicant = models.ForeignKey(Person)
applicant_affirmation = models.BooleanField()
applicant_interest_stmt = models.TextField(verbose_name="In a few sentences, briefly explain why you are interested in this program and what you expect to get out of it")
applicant_school = models.CharField(max_length=100, verbose_name="school (primary)")
applicant_major = models.CharField(max_length=100, verbose_name="major (primary)")
applicant_school_2 = models.CharField(blank=True, max_length=100, verbose_name="school (secondary)")
applicant_major_2 = models.CharField(blank=True, max_length=100, verbose_name="major (secondary)")
gpa_univ = models.DecimalField(max_digits=3, decimal_places=2, verbose_name="GPA (university)")
estimated_grad_semester = models.CharField(max_length=5, verbose_name="estimated graduation semester")
_created = models.DateTimeField(editable=False, blank=False)
_created_by = models.CharField(max_length=150)
_updated = models.DateTimeField(editable=False, blank=False)
_updated_by = models.CharField(max_length=150)
def clean(self):
from django.core.exceptions import ValidationError
cleaned_data = super(Application, self).clean()
if not self.applicant_affirmation:
raise ValidationError('Please check the affirmation checkbox.')
if self.applicant_school_2 == '/':
self.applicant_school_2 = ''
if self.applicant_major_2 == '/':
self.applicant_major_2 = ''
def save(self, *args, **kwargs):
""" On save, update both timestamps """
self._created = datetime.datetime.now()
self._updated = datetime.datetime.now()
return super(Application, self).save(*args, **kwargs)
#end save
def update(self, *args, **kwargs):
""" On update, update only _updated timestamps """
self._updated = datetime.datetime.now()
return super(Application, self).save(*args, **kwargs)
#end update
def __unicode__(self):
return unicode(self.id)
#end unicode
class Meta:
db_table = u'certs_application'
#end meta
Snippet from views.py:
if request.POST:
app_form = ApplicationForm(request.POST)
app_form.fields['estimated_grad_semester'].widget.choices = build_semester_list('', 12)
if app_form.is_valid():
print 'form is valid...'
app_instance = get_object_or_404(Application, id=app_id)
fields = {'program': app_form.cleaned_data['program'],
'status': app_form.cleaned_data['status'],
'applicant_id': application.applicant_id,
'applicant_affirmation': app_form.cleaned_data['applicant_affirmation'],
'applicant_interest_stmt': app_form.cleaned_data['applicant_interest_stmt'],
'applicant_school': app_form.cleaned_data['applicant_school'],
'applicant_major': app_form.cleaned_data['applicant_major'],
'applicant_school_2': app_form.cleaned_data['applicant_school_2'],
'applicant_major_2': app_form.cleaned_data['applicant_major_2'],
'gpa_univ': app_form.cleaned_data['gpa_univ'],
'estimated_grad_semester': app_form.cleaned_data['estimated_grad_semester'],
'_created_by': app_instance._created_by,
'_created': app_instance._created,
'_updated_by': user.eid,
}
try:
application = Application(pk=app_id, **fields)
application.update()
except Exception, exception:
return HttpResponse('Error: ' + str(exception))
return redirect('application_view', app_id=app_id)
else:
print 'app_form is NOT valid'
else:
# -------------------------------------------
# render the application using GET
# -------------------------------------------
app_form = ApplicationForm(admin=admin_user, instance=application)
app_form.fields['estimated_grad_semester'].widget.choices = build_semester_list('', 12)
Final modifications made that resulted in the needed fix:
views.py
if request.POST:
app_form = ApplicationForm(admin=admin_user, data=request.POST)
forms.py
def __init__(self, admin, *args, **kwargs):
super(ApplicationForm, self).__init__(*args, **kwargs)
self.admin = admin
if self.admin:
self.fields['applicant_interest_stmt'].widget.attrs['readonly'] = True
self.fields['applicant_affirmation'].widget.attrs['readonly'] = True
def clean(self):
from django.core.exceptions import ValidationError
cleaned_data = super(ApplicationForm, self).clean()
if not self.admin:
applicant_interest_stmt = cleaned_data.get('applicant_interest_stmt')
applicant_affirmation = cleaned_data.get('applicant_affirmation')
if not applicant_interest_stmt:
msg = u'Please provide an interest statement.'
self._errors["applicant_interest_stmt"] = self.error_class([msg])
if not applicant_affirmation:
msg = u'Please check the affirmation checkbox.'
self._errors["applicant_affirmation"] = self.error_class([msg])
return cleaned_data
NOTE: there is still a lingering problem with getting a non-modifiable setting on the applicant_affirmation Boolean field, but I'll fix that separately from this issue.
you might want to make the admin a golobal to the class
class ApplicationForm(ModelForm):
class Meta:
model = Application
fields = ('program', 'status', 'applicant_affirmation', 'applicant_interest_stmt', 'applicant_school', 'applicant_major', 'applicant_school_2', 'applicant_major_2', 'gpa_univ', 'estimated_grad_semester')
widgets = {
'applicant_interest_stmt': Textarea(attrs={'class': 'form-control', 'rows': 5}),
'estimated_grad_semester': Select(),
}
def __init__(self, admin, *args, **kwargs):
super(ApplicationForm, self).__init__(*args, **kwargs)
self.admin = admin
if self.admin:
self.fields['applicant_interest_stmt'].widget.attrs['disabled'] = 'disabled'
self.fields['applicant_affirmation'].widget.attrs['disabled'] = 'disabled'
def clean(self):
from django.core.exceptions import ValidationError
cleaned_data = super(ApplicationForm, self).clean()
if not self.admin:
applicant_interest_stmt = cleaned_data.get('applicant_interest_stmt')
applicant_affirmation = cleaned_data.get('applicant_affirmation')
if not applicant_interest_stmt:
msg = u'Please provide an interest statement.'
self._errors["applicant_interest_stmt"] = self.error_class([msg])
if not applicant_affirmation:
msg = u'Please check the affirmation checkbox.'
self._errors["applicant_affirmation"] = self.error_class([msg])
return cleaned_data

how to fix the 'AnonymousUser' object has no attribute 'profile' error?

I'm writing a chat app for a hypothetical social network but when I try to open the chat page I give the following error 'AnonymousUser' object has no attribute 'profile' error .
I think there may be problem in the models file but I can't really figure out how to fix it and I'm really confused now!? can anyone give any suggestions??
parts of the chat views.py
def index(request):
if request.method == 'POST':
print request.POST
request.user.profile.is_chat_user=True
logged_users = []
if request.user.username and request.user.profile.is_chat_user:
context = {'logged_users':logged_users}
cu = request.user.profile
cu.is_chat_user = True
cu.last_accessed = utcnow()
cu.save()
return render(request, 'djangoChat/index.html', context)
try:
eml = request.COOKIES[ 'email' ]
pwd = request.COOKIES[ 'password' ]
except KeyError:
d = {'server_message':"You are not logged in."}
query_str = urlencode(d)
return HttpResponseRedirect('/login/?'+query_str)
try:
client = Vertex.objects.get(email = eml)
context = {'logged_users':logged_users}
cu = request.user.profile
cu.is_chat_user = True
cu.last_accessed = utcnow()
cu.save()
if client.password != pwd:
raise LookupError()
except Vertex.DoesNotExist:
sleep(3)
d = {'server_message':"Wrong username or password."}
query_str = urlencode(d)
return HttpResponseRedirect('/login/?'+query_str)
return render_to_response('djangoChat/index.html',
{"USER_EMAIL":eml,request.user.profile.is_chat_user:True},
context_instance=RequestContext(request))
#csrf_exempt
def chat_api(request):
if request.method == 'POST':
d = json.loads(request.body)
msg = d.get('msg')
user = request.user.username
gravatar = request.user.profile.gravatar_url
m = Message(user=user,message=msg,gravatar=gravatar)
m.save()
res = {'id':m.id,'msg':m.message,'user':m.user,'time':m.time.strftime('%I:%M:%S %p').lstrip('0'),'gravatar':m.gravatar}
data = json.dumps(res)
return HttpResponse(data,content_type="application/json")
# get request
r = Message.objects.order_by('-time')[:70]
res = []
for msgs in reversed(r) :
res.append({'id':msgs.id,'user':msgs.user,'msg':msgs.message,'time':msgs.time.strftime('%I:%M:%S %p').lstrip('0'),'gravatar':msgs.gravatar})
data = json.dumps(res)
return HttpResponse(data,content_type="application/json")
def logged_chat_users(request):
u = Vertex.objects.filter(is_chat_user=True)
for j in u:
elapsed = utcnow() - j.last_accessed
if elapsed > datetime.timedelta(seconds=35):
j.is_chat_user = False
j.save()
uu = Vertex.objects.filter(is_chat_user=True)
d = []
for i in uu:
d.append({'username': i.username,'gravatar':i.gravatar_url,'id':i.userID})
data = json.dumps(d)
return HttpResponse(data,content_type="application/json")
and parts of my chat models:
class Message(models.Model):
user = models.CharField(max_length=200)
message = models.TextField(max_length=200)
time = models.DateTimeField(auto_now_add=True)
gravatar = models.CharField(max_length=300)
def __unicode__(self):
return self.user
def save(self):
if self.time == None:
self.time = datetime.now()
super(Message, self).save()
def generate_avatar(email):
a = "http://www.gravatar.com/avatar/"
a+=hashlib.md5(email.lower()).hexdigest()
a+='?d=identicon'
return a
def hash_username(username):
a = binascii.crc32(username)
return a
# the problem seems to be here ??!
User.profile = property(lambda u: Vertex.objects.get_or_create(user=u,defaults={'gravatar_url':generate_avatar(u.email),'username':u.username,'userID':hash_username(u.username)})[0])
and finally parts of the another app(ChatUsers):
class Vertex(models.Model,object):
user = models.OneToOneField(User)
password = models.CharField(max_length=50)
#user_id = models.CharField(max_length=100)
username = models.CharField(max_length=300)
userID =models.IntegerField()
Message = models.CharField(max_length=500)
firstname = models.CharField(max_length=50)
lastname = models.CharField(max_length=50)
email = models.EmailField(max_length=75)
is_chat_user = models.BooleanField(default=False)
gravatar_url = models.CharField(max_length=300,null=True, blank=True)
last_accessed = models.DateTimeField(auto_now_add=True)
Because that user has not logged in yet. Django treat them as AnonymousUser and AnonymousUser does not have the profile property.
If the view is only for logged in user, you can add the login_required decorator to the view function to force the login process. Otherwise, you need to judge whether a user is anonymous with the is_authenticated function.
Reference: Using the Django authentication system

UnboundLocalError local variable <variablename> referenced before assignment

I faced the error when I tried to capture the POST data from a form. Weird, because the same algorithm works with another django app model.
The models:
class Item(models.Model):
code = models.CharField(max_length=200, unique=True)
barcode = models.CharField(max_length=300)
desc = models.CharField('Description',max_length=500)
reg_date = models.DateField('registered date')
registrar = models.CharField(max_length=100)
def __unicode__(self):
return self.code + ' : ' + self.desc
class ItemInfo(models.Model):
model = models.ForeignKey(Item)
supplier = models.ForeignKey(Supplier)
stock_on_hand = models.IntegerField()
stock_on_order = models.IntegerField()
cost = models.IntegerField()
price = models.IntegerField()
unit = models.CharField(max_length=100)
lead_time = models.IntegerField()
def __unicode__(self):
return Item.code + ' : ' + supplier
class ItemForm(ModelForm):
class Meta:
model = Item
class ItemInfoForm(ModelForm):
class Meta:
model = ItemInfo
exclude = ('model')
And the views.py function for non-working (Item) is like this:
def register(request):
csrf_context = RequestContext(request)
current_user = User
if request.user.is_authenticated():
if request.POST:
item = Item()
item_info = ItemInfo()
header_form == ItemForm(data=request.POST,instance=item)
details_form == ItemInfoForm(data=request.POST, instance=item_info)
if header_form.is_valid():
header = header_form.save()
if details_form.is_valid():
details = details_form.save(commit=False)
details.supplier = header
details.save()
return HttpResponseRedirect('/item/')
else:
return render_to_response('error/denied_data_entry.html')
else:
header_form = ItemForm()
details_form = ItemInfoForm()
return render_to_response('item/register.html',{'header_form' : header_form, 'details_form' : details_form}, csrf_context)
else:
return render_to_response('error/requires_login.html', csrf_context)
The working views.py function for another working (Supplier) model is here:
def register(request):
csrf_context = RequestContext(request)
current_user = User
if request.user.is_authenticated():
if request.POST:
supplier = Supplier()
supplier_info = SupplierInfo()
header_form = SupplierForm(data=request.POST, instance=supplier)
details_form = SupplierInfoForm(data=request.POST, instance=supplier_info)
if header_form.is_valid():
header = header_form.save()
if details_form.is_valid():
details = details_form.save(commit=False)
details.model = header
details.save()
return HttpResponseRedirect('/supplier/')
else:
return render_to_response('error/denied_data_entry.html')
else:
return render_to_response('error/denied_data_entry.html')
else:
header_form = SupplierForm()
details_form = SupplierInfoForm()
return render_to_response('supplier/register.html', {'header_form' : header_form, 'details_form' : details_form}, csrf_context)
else:
return render_to_response('error/requires_login.html', csrf_context)
The traceback page shows that the POST did pass some variable. Help me please, I cant figure it out why it works on Supplier, but not Item.
P/S: Sorry for the indentation.
The problem is here:
# ...
header_form == ItemForm(data=request.POST,instance=item)
details_form == ItemInfoForm(data=request.POST, instance=item_info)
You're not assigning, you're comparing.

Categories