I have a backend data and successfully set the data into dropdown but the thing is whenever click on button then it will give me the desire result but the thing is after getting the result, the drop down is like having null values in it so what can i do.
could someone suggest me whenever i click on dropdown then it will get refress or other methods are appreciable.
Thanks!
views.py
def index(request):
sparqlQueries = get_data()
if(request.POST['Case_name'] and request.method =='POST'):
name_cases = sparqlQueries.nameOfCases()
data = {
"cases_name":name_cases,
'flag2':True,
'suffix':'Cases',
'title':'Name of Cases'
}
return render(request,'index.html',context = data)
if(request.method =='POST'):
casename = request.POST['Case_name']
question = request.POST['Question']
#print(casename)
#print(question)
if(casename == 'xyz' and question == 'pqr'):
judges = sparqlQueries.case2_judge_name()
#print(judges)
data = {
"name":judges,
'flag':True,
'suffix':'judges',
'title':'Judge of Case2'
}
return render(request,'index.html', context = data)
...
You're doing it the wrong way:
first of all you check the request method first then check if variable exists
for request.POST['Case_name'] if the Case_name does not exist will raise a key error internal server error, you don't need that for your project so use request.POST.get('Case_name', optional default value)
now for the null dropdown, it's because you didn't add the context you using in the drop down to the newly rendered template, you are not providing the full code but that's usually the reason
Related
I sessions up and running and currently I'm getting the variable 'context_number' set in the browser. In the view I would like to filter on this variable. So I have this in my views.py.
def allcontexts(request):
allcontexts = Context.objects.all()
return render(request, 'context_manager/context_manager.html',
{
'allcontexts':allcontexts,
})
In order to filter I change the second row to the following
allcontexts = Context.objects.filter(context_number=____)
In the blank I want to insert the context_number variable, so context_number[dbcolumn] = context_number[session variable]
I can't seem to figure out the correct syntax, any ideas?
You can access session variables using request.session.get() syntax:
allcontexts = Context.objects.filter(context_number=request.session.get("context_number"))
I am building a web-app using flask appbuilde and stuck at the following issue for a week now.
On the documentation, the instructions seem pretty straight forward:
class MyView(ModelView):
datamodel = SQLAInterface(MyModel)
validators_columns = {
'my_field1':[EqualTo('my_field2', message=gettext('fields must match'))]
}
However, when I implement this exactly, on UI it says "invalid input" even when inputs are correct thus hindering form submission.
My Code(views.py):
class DelModelView(ModelView):
datamodel = SQLAInterface(Dell)
base_filters = [['cap_id', EqualTo, get_user]] #current user
list_columns = ["cap_id", "s_code", "s_name", "sos", "date_of_change"]
#base_order = ("cap_id", "asc")
validators_columns = {
'cap_id':[FilterEqualFunction(get_user, message=_('fields must match'))]
}
def get_user():
return g.user.username
I want to add a validation that checks if while adding new entry cap_id == username.
Am I missing any link here? I have tried multiple solutions but nothing seems to work.
Any help will be appreciated!
I managed to solve this by doing the following:
I removed cap_id from add_coloumns. I am pre-populating it by using the default value, which is current_user and now it works perfectly fine. Yay!!
I am trying to get the Parent Epic / Feature for particular User Stories in Rally. However I am only getting the parent object and I am not sure how to parse it. I have tried dict and dir(object) to get field values but it did not work. I have also tried as following, but I keep on getting something like this instead of fields/values in Parent Object
pyral.entity.PortfolioItem_Capability object at 0x7ff848273850
CODE:
def get_hierarchy(server,username,password,workspace,project,release):
rally = Rally(server, username, password, workspace=workspace, project=project)
criterion = 'Release.Name = "'+release+'" AND Parent != None'
response = rally.get('HierarchicalRequirement',fetch="ObjectID,FormattedID,Name,AcceptedDate,Project,Release,ScheduleState,Parent,Description",query=criterion,limit=5000)
return response
for item in get_hierarchy("rally1.rallydev.com","some.email#address.com","Somepassword","Some Workspace Name","PROJECT NAME","Release Version"):
print item.FormattedID, item.Name, item.ScheduleState, item.Description, item.Parent.Name
The parent is also an object and you have to parse the parent similar to the user story. For a simplistic solution, keep using the dot format. Here is a code snippet that does something similar to the above that should give you a start.
queryString = '(Iteration.StartDate > "2017-08-31")'
entityName = 'HierarchicalRequirement'
response = rally.get(entityName, fetch=True, projectScopeDown=True, query=queryString)
for item in response:
print(item.FormattedID,
item.PortfolioItem.FormattedID,
item.PortfolioItem.Parent.FormattedID,
item.PlanEstimate)
I'm using Python 3.x but I don't see any reason it wouldn't translate to 2.7.
I have a ReactJS component inside a Django template, where a user clicks on a checkout button, posts the item_code and gets redirected to checkout:
onCheckout = () => {
fetch("/onCheckout/", {
method: "POST",
body: JSON.stringify({'item': this.props.item_info.code})
}).then(window.location.replace("/checkout"))
}
A Django view receives the request and stores it in a session.
def onCheckout(request):
if request.method == "POST":
items = request.session.get('items', [])
new_item = json.loads(request.body.decode('utf-8'))['item']
items.append(new_item)
request.session['items'] = items
I am having a issue with storing data in the session. After the first item gets stored correctly in the array, and I then checkout on a second item, the items array starts acting up:
(Pdb) items
['15130BC.ZZ.8042BC.01']
(Pdb) new_item
'5213G-001'
(Pdb) items
['15130BC.ZZ.8042BC.01']
(Pdb) items
['5213G-001']
If I try to access request.session['item'] from any other view function, I get a KeyError.
I am fairly new to Django, any help would be appreciated. Also, I would like to know if there are better alternatives to accomplish the above.
Sessions Config
settings.SESSION_ENGINE = 'django.contrib.sessions.backends.db'
settings.SESSION_CACHE_ALIAS = 'default'
settings.CACHES = {'default': {'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'}}
Some reading on change detection for Django sessions: https://docs.djangoproject.com/en/2.0/topics/http/sessions/#when-sessions-are-saved
Based on your code, it appears to me that the change detection should happen. However, let's try to brute force this, can you add the following line as the last line of your code: request.session.modified = True - see if this fixes your issue?
Update: some basic checks
Can you verify the following
Check if your db backend is configured priestly
If you want to use a database-backed session, you need to add 'django.contrib.sessions' to your INSTALLED_APPS setting. Once you have configured your installation, run manage.py migrate to install the single database table that stores session data.
Check if your session Middleware is enabled
Sessions are implemented via a piece of middleware. The default settings.py created by django-admin startproject has SessionMiddleware activated. To enable session functionality, edit the MIDDLEWARE_CLASSES setting and make sure it contains 'django.contrib.sessions.middleware.SessionMiddleware'.
Update 2: Test the session
Maybe modify a style existing endpoint as follows and see if you are able to store values and persist them in session :
test_keys = request.session.get('test_keys', [])
test_keys.append(random.randint())
request.session['test_keys'] = test_keys
return Response(request.session.get('test_keys', []))
You should see that each time you hit the api, you get a list with one new integer in it in addition to all past values. Lmk how this goes.
I think what I'm trying to achieve is not hard, but I have no clue how to do it hehehehe !
Basically what I need is the feature that we have in Django Admin, when you are creating a new object, if you have a Foreign Key, you can add new data (opening a pop-up), save it and then the select box updates automatically.
What I have is this form:
I know that would be easy to do it with some Javascript, but my point is, Django has some rules, and as far I know, I can't add new data to a form already created, right? Otherwise Django won't validate this form. How could I achieve this?
PS: "Local" is the select box where I want to add new data. The user should be able to create a new Local on this page, instead of going to another page to do it. Thanks :)
Here your question:
I can't add new data to a form already created, right? Otherwise Django won't validate this form. How could I achieve this?
Then the answer:
you are right, django will check values match form value rules. But:
realize that your main form is invoked for twice: on GET and on POST. Between both form executions you make changes on database values trhough your new form. That means that in second main form invocation the value added to database is available:
field1 = forms.ModelChoiceField(queryset= ***1*** )
***1***: on second invocation new value is already available on field1.
Then, you don't should to be afraid about this subject, the new value will be available on form on your main form POST request.
Nothing wrong with updating the value using javascript as long the key in your new combo box has the right key in the database then it should be ok.
Call this function after you saved the last entry.
function refreshLocal(){
$.get(window.location.href, '', function(html){
// change the id to the local combox's id
var serverLocalDropBox = $(html).find('#id_local');
if (serverLocalDropBox.length){
$('#id_local').replaceWith(serverLocalDropBox);
}
})
}
If you don't want to use javascript solution, you can post the form with refresh flag and on the server side if you see that flag just don't validate and return the form as is. Since you have a new entry in the foreignkey it will automatically update the queryset to include the new entry.
function serverRefreshLocal(){
var $form = $('#your_form_id');
$form.append('<input type="hidden" name="refresh" value="true" />');
// you can use ajax submit and ajax refresh here if you don't want to leave the page
$form.submit();
}
// Server Side
def your_form_post_view(request):
if request.POST.get('refresh', 'false') == 'true':
# initial is the trick to save user input
your_form = YourForm(initial=request.POST)
context = {
'form': your_form,
}
return render(request, 'your_template.html', context)
# your view code goes here