django Model form with initial and data values - django

I am trying to set my model form with data as well as initial_dict. They both are working fine indivisiually, but when i put both in the method call, Initial does not work.
here is the code.
state = Territory.objects.filter(abbreviation=request.GET.get('territory', ''))
if state:
initial_dict['state'] = state.get()
ctx['add_customer'] = AddCustomer(data=request.GET, initial=initial_dict)
But the state (Dropdown) does not get selected.
This works fine
ctx['add_customer'] = AddCustomer(initial=initial_dict)
Ideas?

This is actually solved my problem.
initial_dict = request.GET.dict()
state = Territory.objects.filter(abbreviation=initial_dict.get('state', ''))
if state:
initial_dict['state'] = state.get()
ctx['add_customer'] = AddCustomer(initial=initial_dict)
Converted data to Python Dict & use only Initial.
I am still not sure why that problem was occurring.

Related

Django form data loop

How can I loop through form data where the ending part could be 1,2,3,4 and so on, and store in the DB without hardcoding the DB like below so each description would be on its own line but one person could post description1-10 and the other 10-27 and so on
for example instead of say this
order.description_1 = request.POST.get('description1')
order.length_1 = request.POST.get('length1')
order.width_1 = request.POST.get('width1')
order.depth_1 = request.POST.get('depth1')
order.weight_1 = request.POST.get('weight1')
order.description_2 = request.POST.get('description2')
order.length_2 = request.POST.get('length2')
order.width_2 = request.POST.get('width2')
order.depth_2 = request.POST.get('depth2')
order.weight_2 = request.POST.get('weight2')
currently the form passes request.POST.get('description1') and with a limit of request.POST.get('description5') but would like each description on its own row and not be subject to a hardlimit and uses a bit of javascript to append the x value to the name. The postdata form is also hardcoded so not using forms.py
The request.POST is a python dictionary, so you can loop through it like this:
for key, value in request.POST.items():
print(key, value)
# set the property for order
# you can work on key and change it if need
setattr(order, key, value)
For a better implementation of this requirement, you can use django forms with ArrayField fields:
django simple array field
how-to-define-arrayfield-to-django-forms

SQLAlchemy adding/updating in for loop: updating not working

I'm trying to do the following: loop through a series of records, if one already exists, I update it. If it doesn't exist, I add it.
For some reason, the adding is working fine, but the updating is not occurring. here's the code:
for interchange in data:
ltype='asdf'
plink='qwer'
e = Part.query.filter_by(interchange=interchange, light_type=ltype).first()
if e is None:
notpresent = notpresent + 1
p = Part(interchange=interchange,light_type=ltype,partslink=plink,ptype=ptype)
db.session.add(p)
else:
present = present + 1
e.partslink = plink
e.ptype = ptype
db.session.commit()
I print out the present and notpresent variables and both are > 0.
Am I handling the update part incorrectly when the record is found? That portion is not getting saved.
you are missing a line:
# ...
else:
present = present + 1
e.partslink = plink
e.ptype = ptype
db.session.add(e) # here 'add' is adding changes to the session, not a new item.
you cannot commit changes if you do not register them.

Accessing instance attributes that start with a certain string

In my view, I'm trying to blank/delete a number of fields that start with real_.
I can do something like:
plan = get_object_or_404(Plan, pk=self.kwargs['plan_id'])
plan.real_time = None
plan.real_date = None
plan.real_comments = None
plan.real_whatever = None
....
plan.save()
However I guess there must be a way to do this programmatically. All I'd need to do is access the names of the the fields, compare whether it indeed starts with real_ and then update that field.
I'm using get_fields() (as per the documentation). I'm not sure though how to do the last part though.
Following is the code of my view:
plan = get_object_or_404(Plan, pk=self.kwargs['plan_id'])
plan_fields = plan._meta.get_fields()
for field in plan_fields:
if field.name[:5] == "real_":
plan.<not sure what to do here> = None
plan.save()
I guess I must be overlooking something small. Any pointer?
Using Django 1.9.
if field.name[:5] == "real_":
setattr(plan, field.name, None)
Python doc.
I would recommend something nice and neat like this:
plan = get_object_or_404(Plan, pk=self.kwargs['plan_id'])
real_fields = [field for field in plan._meta.get_fields() if field.name.startswith('real_')]
for field in real_fields:
setattr(plan, field, None)
plan.save()
This is partially opinion based, but I feel that the use of the list comprehension and .startswith() are slightly more Pythonic.

Django -- Updating specific values in a resulting queryset

What is wrong in these lines:
for i in message_list:
message_stream = Messages.objects.filter(OrderID = i.OrderID).order_by('-MessageLocalID')
if message_stream[0].MessageTypeName != 'MessageAck':
message_stream[0].status = message_stream[0].MessageTypeName
message_stream[0].save()
The status field doesn't get saved here in the DB. What I do misunderstand here?
The problem was in the DB itself, the status field, where it should be updated with new values,wasn't able to receive values more than 2 characters. I used Django DB migration and extended the status field, solved the problem.
This command worked like a charm with no problems:
NpMessages.objects.filter(NPOrderID = i.NPOrderID, MessageTypeName = 'Request').update(status = message_stream[1].MessageTypeName)
and get rid of the save statement, as it didn't work eitherway!!!

TDD Django tests seem to skip certain parts of the view code

I'm writing some tests for a site using django TDD.
The problem is that when I manually go to the testserver. Fill in the form and submit it then it seems to works fine. But when I run the test using manage.py test wiki it seems to skip parts of the code within the view. The page parts all seem to work fine. But the pagemod-parts within the code and even a write() I created just to see what was going on seems to be ignored.
I have no idea what could be causing this and can't seem to find a solution. Any ideas?
This is the code:
test.py
#imports
class WikiSiteTest(LiveServerTestCase):
....
def test_wiki_links(self):
'''Go to the site, and check a few links'''
#creating a few objects which will be used later
.....
#some code to get to where I want:
.....
#testing the link to see if the tester can add pages
link = self.browser.find_element_by_link_text('Add page (for testing only. delete this later)')
link.click()
#filling in the form
template_field = self.browser.find_element_by_name('template')
template_field.send_keys('homepage')
slug_field = self.browser.find_element_by_name('slug')
slug_field.send_keys('this-is-a-slug')
title_field = self.browser.find_element_by_name('title')
title_field.send_keys('this is a title')
meta_field = self.browser.find_element_by_name('meta_description')
meta_field.send_keys('this is a meta')
content_field = self.browser.find_element_by_name('content')
content_field.send_keys('this is content')
#submitting the filled form so that it can be processed
s_button = self.browser.find_element_by_css_selector("input[value='Submit']")
s_button.click()
# now the view is called
and a view:
views.py
def page_add(request):
'''This function does one of these 3 things:
- Prepares an empty form
- Checks the formdata it got. If its ok then it will save it and create and save
a copy in the form of a Pagemodification.
- Checks the formdata it got. If its not ok then it will redirect the user back'''
.....
if request.method == 'POST':
form = PageForm(request.POST)
if form.is_valid():
user = request.user.get_profile()
page = form.save(commit=False)
page.partner = user.partner
page.save() #works
#Gets ignored
pagemod = PageModification()
pagemod.template = page.template
pagemod.parent = page.parent
pagemod.page = Page.objects.get(slug=page.slug)
pagemod.title = page.title
pagemod.meta_description = page.meta_description
pagemod.content = page.content
pagemod.author = request.user.get_profile()
pagemod.save()
f = open("/location/log.txt", "w", True)
f.write('are you reaching this line?')
f.close()
#/gets ignored
#a render to response
Then later I do:
test.py
print '###############Data check##################'
print Page.objects.all()
print PageModification.objects.all()
print '###############End data check##############'
And get:
terminal:
###############Data check##################
[<Page: this is a title 2012-10-01 14:39:21.739966+00:00>]
[]
###############End data check##############
All the imports are fine. Putting the page.save() after the ignored code makes no difference.
This only happens when running it through the TDD test.
Thanks in advance.
How very strange. Could it be that the view is somehow erroring at the Pagemodification stage? Have you got any checks later on in your test that assert that the response from the view is coming through correctly, ie that a 500 error is not being returned instead?
Now this was a long time ago.
It was solved but the solution was a little embarrassing. Basically, it was me being stupid. I can't remember the exact details but I believe a different view was called instead of the one that I showed here. That view had the same code except the "skipped" part.
My apologies to anyone who took their time looking into this.