How to write a logout function for my django app? - html

Here is views.py:
def authent(request):
user = request.POST['username']
passw = request.POST['password']
featureDetail = []
loginrole = People_Login.objects.get(User_Name = user, Password = passw)
features = Role_FGroup_FSubGroup_FItems_Map.objects.filter(Role_Id = loginrole.id)
for p in features:
dic = {}
dic['ID'] = p.id
dic['Role_ID'] = p.Role_Id.id
dic['FGID'] = p.Feature_Group_Id.id
dic['FSGID'] = p.Feature_SubGroup_Id.id
dic['FIID'] = p.Feature_Items_Id.id
dic['SFGNAME'] = p.Feature_Group_Id.Name
dic['SFSGNAME'] = p.Feature_SubGroup_Id.Name
dic['SFINAME'] = p.Feature_Items_Id.Name
featureDetail.append(dic)
featuresgroups = Role_Feature_Group_Map.objects.filter(Role_Id = loginrole.Role_Id.id)
request.session['feature_list'] = featureDetail
request.session['featuresgroups'] = featuresgroups
return render_to_response('UAM/index.html',{"contacts":featureDetail,'len':len(featureDetail)-1,'test1':"shiva",'test2':"shiva","featuresgroups":featuresgroups})
For this authent function how to write my logout function
(as I am new to Django)? Please go easy and give me the code for logout function.

I suggest using Django's built in authentication features instead of rolling out your own. Otherwise, you're bound to make many mistakes (such as storing plain text passwords, which I see it's what you're doing) and reinvent many wheels (such as session handling, groups and permissions, etc). If you need to store more information about users than Django supports, you can do it in the form or user profiles.
Anyway, if by "logged on" you mean "having those values in the session", to "log out" you just need to remove them, no?

It really is this easy:
from django.contrib.auth import logout
def logout_page(request):
logout(request)
return HttpResponseRedirect('/')

Related

Are my Rails methods/helper functions executing every time anyone does a GET request to the server, in parallel? Is this an issue?

My website is mostly to display results, so the admin enters the results and they are rendered nicely for the users/clients. Currently, in my main_controller.rb and other controllers I have functions for the main index page...
def index
#next_tournament = helpers.next_tournament()
#last_tournament = helpers.last_tournament()
#last_tournament_date_display = helpers.last_tournament_date_display(#last_tournament)
#next_tournament_date_display = helpers.next_tournament_date_display(#next_tournament)
#current_season = #last_tournament.season_year
#aoys = helpers.display_aoy(#last_tournament.id)
#aoy_diff = helpers.aoy_point_diff(#aoys)
#individual_winners = helpers.individual_winners(#last_tournament.id)
#team_winners = helpers.team_winners(#last_tournament.id)
#big_bass_winners = helpers.big_bass_winners(#last_tournament.id)
#total_club_stats = helpers.total_club_stats()
#annual_club_stats = helpers.annual_club_stats(#current_season )
...
end
Does this mean, that for every person that navigates to my main index page the server will re-run these functions and spit out the result?
I'm trying to understand what happens on the server side. Would this be a problem? Most of these functions would only change when a new result is entered. Is it best practice to do something in the code, so that the function is only re-ran when any of the variables in the equation change, and otherwise static?

I'm having trouble with sending a form using POST to retrieve data in R

I'm having trouble collecting doctors from https://www.uchealth.org/providers/. I've found out it's a POST method but with httr I can't seem to create the form. Here's what I have
url = url = 'https://www.uchealth.org/providers/'
formA = list(title = 'Search', onClick = 'swapForms();', doctor-area-of-care-top = 'Cancer Care')
formB = list(Search = 'swapForms();', doctor-area-of-care = 'Cancer Care')
get = POST(url, body = formB, encode = 'form')
I'm fairly certain formB is the correct one. However, I can't test it since I yield an error when trying to make the list. I believe it is because you can't use "-" characters when naming although I could be wrong on that. Could somebody help please?
I am unable to comment properly but try this to create an list. Code below worked for me.
library(httr)
url = 'https://www.uchealth.org/providers/'
formB = list(Search = 'swapForms();', `doctor-area-of-care` = 'Cancer Care')
get = POST(url, body = formB, encode = 'form')
When you are creating names with spaces or some other special character you have to put it into the operator above.

How to insert Liferay blogs entry programmatically

I use Liferay 6.0.6 and i need to insert the blogs entry programmatically from my custom Portlet or scheduled job.
I found the class BlogsEntryLocalServiceUtil but don't know how to use it.
Thank you.
This is the solution:
Company company = CompanyLocalServiceUtil.getCompanyById(MY_COMPANY_ID);
Role adminRole = RoleLocalServiceUtil.getRole(company.getCompanyId(),"Administrator");
List<User> adminUsers = UserLocalServiceUtil.getRoleUsers(adminRole.getRoleId());
//GET USER ADMIN
User adminUser = null;
for (User user : adminUsers){
if (user.getEmailAddress().equals(MY_ADMIN_EMAIL)){
adminUser = user;
break;
}
}
if (adminUser!=null) {
long userID = adminUser.getUserId();
long groudID = adminUser.getGroupIds()[0];
PrincipalThreadLocal.setName(userID);
PermissionChecker permissionChecker=PermissionCheckerFactoryUtil.create(adminUser, true);
PermissionThreadLocal.setPermissionChecker(permissionChecker);
Calendar displayDate =CalendarFactoryUtil.getCalendar(TimeZone.getTimeZone(StringPool.UTC));
boolean allowPingbacks = true;
boolean allowTrackbacks = true;
int actionPublish = WorkflowConstants.ACTION_PUBLISH;
ServiceContext serviceContext = new ServiceContext();
serviceContext.setWorkflowAction(actionPublish);
serviceContext.setAssetCategoryIds(new long[]{category});
serviceContext.setCreateDate(displayDate.getTime());
serviceContext.getExpandoBridgeAttributes().put("key1", value1);
serviceContext.getExpandoBridgeAttributes().put("key2", value2);
serviceContext.setAddGuestPermissions(true);
serviceContext.setScopeGroupId(groudID);
//INSERT BLOGS ENTRY
BlogsEntryLocalServiceUtil.addEntry(userID, title, content, displayDate.get(Calendar.MONTH), displayDate.get(Calendar.DAY_OF_MONTH), displayDate.get(Calendar.YEAR), displayDate.get(Calendar.HOUR), displayDate.get(Calendar.MINUTE), allowPingbacks, allowTrackbacks, new String[]{}, serviceContext);
}
You have addEntry method available in the class you mentioned i.e. BlogsEntryLocalServiceUtil, just pass the required parameters and you will be able to create a blog entry.
but don't know how to use it.
For this, you can try to look into portal-impl folder of liferay source and find all the java sources available there to find how to implement them.

Save buttons missing in django admin

I have 2 simple models:
class Doll(models.Model):
name = models.CharField(max_length=32)
doll_type = models.CharField(max_length=16, choices=DOLL_TYPE_CHOICES)
mark = models.CharField(max_length=48, help_text='trademark on the body of the doll', default='')
body = models.CharField(max_length=16, choices = BODY_CHOICES)
factory = models.CharField(max_length=24, choices=FACTORY_CHOICES)
class DollLink(models.Model):
doll = models.ForeignKey(Doll)
link_type = models.CharField(max_length=16, choices=LINK_TYPE_CHOICES)
url = models.URLField(default='')
In admin.py:
class DollLinkInline(admin.TabularInline):
model = DollLink
fields = ('link_type', 'url')
extra = 1
class DollAdmin(admin.ModelAdmin):
list_display = ('name', 'doll_type', 'body', 'factory')
list_filter = ('doll_type', 'body', 'factory')
inlines = (DollLinkInline,)
admin.site.register(Doll, DollAdmin)
If I want to add a new Doll or edit an existing one, then the save buttons are missing. It seems to me that it's related to inlines, cause if I remove the inline, the save buttons are back, and can add/edit Doll and DollLink separately. But if I put back the inline, again no save option. No js error on page.
I used django and inlines previously, and never experienced anything like that, nor found any similar issues with google.
My django version is 1.6.5, use MySQL and Cloud9 IDE.

How to begin debugging POST and GET requests in Django and Python Shell

I have written the following code.
The issue that I am having is that the database is not being updated and a new record is not being made. I am assuming that the way I am retrieving my POST are incorrect but that's why I am asking where do I begin to debug? I have created template variables for quantity,action,building, and test. When I try to call them in the html {{ test }} for example nothing ever shows up even the one that is hardcoded. I used firebug and the form is indeed posting the values that should be posted.
the form consists of two drop down menus one for action and one for building. A numerical input quantity, a text box and a submit button. If anyone can offer me some advice it would be appreciated. I really don't understand why the hardcoded one doesn't show up
If you need any more information please let me know.
def update(request,Type_slug, slug, id):
error = False
Slug = slug
ID = id
Type = Type_slug
test = 'test'
quantity = request.POST['Qty']
action = request.POST['Action']
building = request.POST['Building']
comments = request.POST['Comments']
if Type == 'Chemicals':
item = Chemicals.objects.filter(S_field=Slug, id= ID)
New_Record = ChemicalRecord(Name=item.Name,Barcode=item.Barcode,Cost=item.Cost,Action=action,Building=building)
if building == 'Marcus':
building_two = 'Pettit'
elif building =='Pettit':
building_two ='Marcus'
Record_one = ChemicalRecord.objects.filter(Barcode=New_Record.Barcode).filter(Building=New_Record.Building)
if Record_one:
Record_one = ChemicalRecord.objects.filter(Barcode=New_Record.Barcode).filter(Building=New_Record.Building).latest('id')
New_Record.On_hand = Record_one.On_hand
else:
New_Record.On_hand = 0
if action == 'Receiving':
New_Record.On_hand = New_Record.On_hand+quantity
elif action == 'Removing':
New_Record.On_hand = New_Record.On_hand-quantity
Record_two = ChemicalRecord.objects.filter(Barcode=New_Record.Barcode).filter(Building=building_two)
if Record_two:
Record_two = ChemicalRecord.objects.filter(Barcode=New_Record.Barcode).filter(Building=building_two).latest('id')
Record_two_qty = Record_two.On_hand
else:
Record_two_qty = 0
New_qty = New_Record.On_hand+Record_two_qty
Chemicals.objects.filter(Barcode=obj.Barcode).update(On_hand=New_qty)
New_Record.save()
You can use import pdb;pdb.set_trace() for debugging.