Django 'the view page didn't return an HttpResponse object.' - django-1.2

I am a newbie for Django. I have had an error like title during making pages.
my system information is Django1.2, Ubuntu12.
There already has been same as my error on stackorverflow - http://goo.gl/bK5msW
def register_page(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
user = User.objects.create_user(
username=form.cleaned_data['username'],
password=form.cleaned_data['password1'],
email=form.cleaned_data['eamil']
)
return HttpResponseRedirect('/')
else:
form = RegistrationForm()
return render_to_response('registration/register.html', variables)

Looking like some issue with indentation, this should work for you.
def register_page(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
user = User.objects.create_user(
username=form.cleaned_data['username'],
password=form.cleaned_data['password1'],
email=form.cleaned_data['email']
)
return HttpResponseRedirect('/')
else:
form = RegistrationForm()
return render_to_response('registration/register.html', variables)

Related

Downloading content from URL without prompting for authentication in Grails

I am working on a web app programmed in Grails. I have a page used to display a certain report and these reports can contain attachments. The attachment is stored in documentum and currently, when the user clicks on it, it is only a link to the location in documentum where the attachment is stored and prompts the user for his credentials. My app has documentum credentials stored in the configuration file therefore I want to use those rather than forcing the user to enter his own credentials. I am using RESTful services to retrieve link but I am trying to find a way to use the link to download directly to the users computer.
private def getFileInfo(def id, def subject) {
// product show view needs the following four lists to display the document information correctly
def ATRReportInstance = ATRReport.findByTrackingNumber(id)
def linkList = []
def nameList = []
def formatList = []
def idList = []
// open up a connection to the documentum server
def doc = connectToDocumentum()
if (!doc) return
def rest = doc.rest
def response = doc.response
if (response.status == 200) {
// retrieve the folder for this product (the name of this folder is the product's ID)
def rObjectId = rest.get(documentumServer + "/repositories/" + documentumfilestore + "?dql=select r_object_id from dm_folder where any r_folder_path='" + atrreportfolderpath + "/" + id + "'") {
auth authuser, authpass
}
// get the folder's ID from the folder object retrieved above
def folderObjectID
rObjectId.json.entries.each {
entry - >
folderObjectID = entry.content.properties.r_object_id
}
// get all of the documents in the product's MSDS folder using the folder ID retrieved above
def resp = rest.get(documentumServer + "/repositories/" + documentumfilestore + "?dql=select r_object_id, object_name, a_content_type, subject from cbs_document where any i_folder_id= '" + folderObjectID + "'") {
auth authuser, authpass
}
// cycle through the documents above to populate the four MSDS document information lists
def x = 0
resp.json.entries.each {
entry - >
if (entry.content.properties.subject == subject) {
// get the document's content object from the document's ID
def content = rest.get(documentumServer + "/repositories/" + documentumfilestore + "/objects/" + entry.content.properties.r_object_id + "/contents/content" + "?media-url-policy=local") {
auth authuser, authpass
}
if (entry.content.properties.r_object_id != null && ATRReportInstance.inactiveFiles != null && ATRReportInstance.inactiveFiles.contains(entry.content.properties.r_object_id.toString())) {} else {
linkList[x] = getLink(content.json.links, "enclosure")
if (linkList[x].contains("format=msg"))
linkList[x] = linkList[x].toString().substring(0, linkList[x].toString().indexOf("content-media")) + "content-media.msg"
formatList[x] = entry.content.properties.a_content_type
nameList[x] = entry.content.properties.object_name
idList[x] = entry.content.properties.r_object_id
x++
}
}
}
return [linkList: linkList, nameList: nameList, formatList: formatList, idList: idList]
} else {
// return null if documentum is unavailable
flash.message = message(code: 'error.documentum.unavailable')
return null
}
}
I'm thinking writing another function that can take in a URL and download the document to the user might work, but I can't figure how to retrieve that document within Grails.
If you want to bypass login you could either setup a SSO solution (requires some work for DCTM) or do a function as you suggest. However you should consider the licensing terms when doing this.
Here is the solution I implemented and that worked. It is a method that downloads a file in documentum using authentication credentials found in a configuration file.
def exportAttachment() {
//uses parameters from gsp file
def url = params.url
def name = params.name
def format = params.format
def extension
//find proper extension
for (s in documentumExtMap) {
if (s.value.equals(format)) {
extension = s.key
}
}
def connection = new URL(url).openConnection()
def remoteAuth = "Basic " + "${authuser}:${authpass}".bytes.encodeBase64()
connection.setRequestProperty("Authorization", remoteAuth)
def dataStream = connection.inputStream
response.setContentType("application/octet-stream")
response.setHeader('Content-disposition', 'Attachment; filename=' + name + '.' + extension)
response.outputStream << dataStream
response.outputStream.flush()
}
The method has three parameters: url, name, format.
Url is the location of the file in documentum.
Name is the name of the download client side
Format is the type of file that is being downloaded. In my case, I had to use this to get the proper extension needed for the file.

Groovy httpbuilder post list params

I'm trying to consume a web service from my grails project. I'm using httpbuilder 0.7.2. Below is my http client.
static def webServiceRequest(String baseUrl, String path, def data,method=Method.GET,contentType=ContentType.JSON){
def ret = null
def http = new HTTPBuilder(baseUrl)
http.request(method, contentType) {
uri.path = path
requestContentType = ContentType.URLENC
if(method==Method.GET)
uri.query = data
else
body = data
headers.'User-Agent' = 'Mozilla/5.0 Ubuntu/8.10 Firefox/3.0.4'
response.success = { resp, json ->
println "response status: ${resp.statusLine}"
ret = json
println '--------------------'
}
}
return ret
}
The issue is coming when i'm trying to send something like this:
def input = [:]
input['indexArray'] = [1,5]
api call
def response = webServiceRequest(url,uri,input,Method.POST)
when i'm printing the value of post data in my server it shows only last value of list.
{"indexArray":"5"}
it should show both 1 and 5
If you want to send json data using contenttype application/x-www-form-urlencoded you have to explicitly convert the data before adding it to the body, you can use (data as JSON).
I am using RESTClient (nice convenience wrapper on HTTPBuilder, https://github.com/jgritman/httpbuilder/wiki/RESTClient). It is as simple as this with Spock.
RESTClient restClient = new RESTClient("http://localhost:8080")
restClient.contentType = ContentType.JSON
Also it automatically parses the JSON data, so my Spock test is:
when: "we check the server health"
HttpResponseDecorator response = restClient.get([path : "/health"]) as HttpResponseDecorator
then: "it should be up"
response != null
200 == response.status
'application/json' == response.contentType

Grails redirect after uploadForm

I am trying to redirect a page after a g:uploadForm has submitted.
my g:uploadForm action is save.
the save is as follows:
#Transactional
def save(DesignCategory designCategoryInstance) {
if (designCategoryInstance == null) {
notFound()
return
}
if (designCategoryInstance.hasErrors()) {
respond designCategoryInstance.errors, view: 'create'
return
}
def disotypeFile = request.getFile('disotype1')
if(!disotypeFile.empty){
print('here')
def fname = disotypeFile.getOriginalFilename()
def fileAtt = new FileAttachment()
fileAtt.originalFilename = fname
fileAtt.newFilename = "disotype-"
fileAtt.fileURI = '/Users/work/Desktop/files/' + fileAtt.newFilename
disotypeFile.transferTo(new File(fileAtt.fileURI))
response.sendError(200, 'Done')
fileAtt.save(flush: true)
designInstance.disotype = fileAtt;
}
designCategoryInstance.save flush: true, failOnError:true
flash.message = message(code: 'default.created.message', args: [message(code: 'designCategoryInstance.label', default: 'DesignCategory'), designCategoryInstance.id])
redirect designCategoryInstance
}
This gives the following error:
Cannot issue a redirect(..) here. The response has already been committed either by another redirect or by directly writing to the response.. Stacktrace follows:
Message: Cannot issue a redirect(..) here. The response has already been committed either by another redirect or by directly writing to the response.
This does work if i take out the
def disotypeFile = request.getFile('disotype1')
but obviously I cannot get the file.
any ideas?
Try to remove line:
response.sendError(200, 'Done')

Logic block in Grails URLMappings

My site has urls like 'http://someRandomUsername.mysite.com'.
Sometimes users will try urls like
'http://www.someRandomeUsername.mysite.com'. I'd like to have some
logic in my url mappings to deal with this.
With the mappings below when I hit the page , with or without the
unneeded www, I get:
2012-03-01 14:52:16,014 [http-8080-5] ERROR [localhost].[/ambit] -
Unhandled exception occurred whilst decorating page
java.lang.IllegalArgumentException: URL mapping must either provide a
controller or view name to map to!
Any idea how to accomplish this? The mapping is below.
Thanks!
Jason
static mappings = {
name publicMap: "/$action?/$id?" {
def ret = UrlMappings.check(request)
controller = ret.controller
userName = ret.userName
}
}
static check =
{ request ->
def tokens = request?.serverName?.split(/\./) as List ?: []
def ret = [controller:'info']
if(tokens.size() > 3 && token[0] == 'www')
{
ret.userName = tokens[1]
ret.controller = 'redirect'
ret.action = 'removeWWW'
}
else if(tokens.size() == 3)
{
ret.userName = tokens[0]
ret.controller = 'info'
}
return ret
}
Honestly, like DmitryB said, the best way to do this is via the web server, whether it's IIS, Apache, or Tomcat.
Having said that, I feel the best way to accomplish this in Grails would be using filters.
You could create something like this in your ~/conf directory:
public class StripFilters {
def filters = {
stripWWWFilter(controller: '*', action: '*') {
before = {
def tokens = request.serverName.tokenize(/\./) ?: []
if(tokens.size() > 3 && tokens[0] == 'www') {
def url = request.request.requestURL.toString().replace('www.', '')
redirect([url:url, params: [userName: tokens[1]], permanent: true])
return false
}
}
}
}
}
This should do the trick.

webflow in grails application

how can i redirect to the same state more than one time using web flow
ex:
on('submit'){
def destinationInstance = Destination.get(params.destination)
def destinationGroupsInstance = DestinationGroup.get(params.destinationGroups)
def h = destinationInstance.addToDestinationGroups(destinationGroupsInstance)
}.to('flowList')
what i need is how to enter to this state more than one time until destinations ends
thx
on('submit'){
def destinationInstance = Destination.get(params.destination)
def destinationGroupsInstance = DestinationGroup.get(params.destinationGroups)
def h = destinationInstance.addToDestinationGroups(destinationGroupsInstance)
}.to{
(condition or while loop or for loop)
if success then
return "<state name>"
else
return "flowList"
}
Reference:
http://livesnippets.cloudfoundry.com/docs/guide/2.%20Grails%20webflow%20plugin.html
Well, you'd probably have something like the following code, which is untested but may give you a general idea.
def destinationFlow = {
initialize {
action {
flow.destination = Destination.get(params.id)
}
on('success').to 'destinationList'
}
destinationList {
render(view: 'destinationList')
on('addDestination') {
def destinationGroup = DestinationGroup.get(params.destinationGroupId)
flow.destination.addToDestinationGroups(destinationGroup)
}.to 'destinationList'
on('finish').to 'done'
}
done {
flow.destination.save()
redirect(...) // out of the flow
}
}
You'll need buttons on your destinationList view that invoke the 'addDestination' or 'finish' actions. See the WebFlow documentation and Reference Guide.

Resources